Skip to content

Instantly share code, notes, and snippets.

@wshayes
Last active March 24, 2016 11:47
Show Gist options
  • Select an option

  • Save wshayes/775ec6cef36eb5b2be8a to your computer and use it in GitHub Desktop.

Select an option

Save wshayes/775ec6cef36eb5b2be8a to your computer and use it in GitHub Desktop.
Waiting for async event for custom element
import { HttpClient } from 'aurelia-fetch-client';
import { CompositionTransaction } from 'aurelia-framework';
export class YearToDateGauge {
static inject = [HttpClient, CompositionTransaction];
constructor(http, compositionTransaction) {
this.http = http;
this.compositionTransaction = compositionTransaction;
// https://github.com/aurelia/framework/issues/367
this.compositionTransaction = compositionTransaction;
this.compositionTransactionNotifier = null;
}
// From Rob Eisenberg:
// If you ever wanted to use view caching, using created() would not work because when a view is
// cached its created callback is only called once on the initial creation, not when it is reused.
// However, bind, attached, detached and unbind are always called. Also, in many cases, the async
// composition operation is dependent on some data, which would not usually be available until the
// bind phase. For the specific example above, it might not matter.
bind() {
this.compositionTransactionNotifier = this.compositionTransaction.enlist();
// return a promise that resolves when the data is retrieved
this.http.fetch('/books/')
.then(data => {
this.books = data; // store locally
// done loading data, allow the attached() hook to fire
this.compositionTransactionNotifier.done();
return data;
});
}
// fires only after the promise from `bind()` either resolves or rejects
attached() {
// update the DOM here, e.g. draw a chart, etc
this.numBooks = this.books.length; // the user is guaranteed that this.books will be availaible
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment