Skip to content

Instantly share code, notes, and snippets.

@istrau2
Forked from niieani/app.html
Last active August 30, 2017 21:28
Show Gist options
  • Save istrau2/524b94cc960456499bbb306fe1491e4a to your computer and use it in GitHub Desktop.
Save istrau2/524b94cc960456499bbb306fe1491e4a to your computer and use it in GitHub Desktop.
Asyc Aurelia Bindings
<template>
<!-- Simple usage: -->
<h1>message: ${message1}</h1>
<!-- With a placeholder: -->
<h1>message: ${message1 || '...'}</h1>
<!-- With an unresolved return: -->
<h1>message: ${message2}</h1>
</template>
import {bindableAsync} from './bindable-async';
export class App {
@bindableAsync()
get message1() {
return this.message3;
}
@bindableAsync({
unresolvedReturn: '...'
})
get message2() {
return this.message3;
}
get message3() {
return new Promise((resolve) => setTimeout(() => resolve('Hello World!'), 2000));
}
}
const defaultOptions = {
unresolvedReturn: undefined
};
export function bindableAsync(options) {
const _options = {
...defaultOptions,
...options
};
return function(target, name, descriptor) {
if (!Promise || typeof Promise.prototype.then != 'function') {
return;
}
let oldGetter = descriptor.get;
descriptor.get = function observableGetter() {
const promise = oldGetter.call(this);
if (promise.hasOwnProperty('value')) {
return promise;
}
return _options.unresolvedReturn;
};
descriptor.get.getObserver = function(obj) {
return {
subscribe: function(context, binding) {
if (oldGetter.subscribe) {
oldGetter.subscribe(context, binding);
}
const promise = oldGetter.call(obj);
if (promise && promise.then && typeof promise.then === 'function') {
promise.then(value => binding.updateTarget(value));
}
},
unsubscribe: function (...args) {
if (oldGetter.unsubscribe) {
oldGetter.unsubscribe.apply(undefined, args);
}
}
}
};
}
}
<!doctype html>
<html>
<head>
<title>Aurelia</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body aurelia-app>
<h1>Loading...</h1>
<script src="https://jdanyow.github.io/rjs-bundle/node_modules/requirejs/require.js"></script>
<script src="https://jdanyow.github.io/rjs-bundle/config.js"></script>
<script src="https://jdanyow.github.io/rjs-bundle/bundles/aurelia.js"></script>
<script src="https://jdanyow.github.io/rjs-bundle/bundles/babel.js"></script>
<script>
require(['aurelia-bootstrapper']);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment