Created
February 14, 2019 10:38
-
-
Save bryandh/ae72ba24e20afbcd0a3d2b33365013c8 to your computer and use it in GitHub Desktop.
AsyncBindingBehavior - awaits a called promise and returns the result to the view
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class AsyncBindingBehavior { | |
private bind(binding: any, source: any): void { | |
binding.originalupdateTarget = binding.updateTarget; | |
binding.updateTarget = (target: Promise<any>) => { | |
// When we have a promise | |
if (typeof target.then === 'function') { | |
// Set temp value to loading so we know its loading | |
binding.originalupdateTarget('Loading...'); | |
// Process the promise | |
target | |
.then((response) => { | |
// Make sure the binding target is still available | |
if (binding.originalupdateTarget) | |
binding.originalupdateTarget(response); | |
}) | |
.catch((error) => binding.originalupdateTarget('Promise failed')); | |
} else | |
binding.originalupdateTarget(target); | |
}; | |
} | |
private unbind(binding: any) { | |
binding.updateTarget = binding.originalupdateTarget; | |
binding.originalupdateTarget = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment