framework icon indicating copy to clipboard operation
framework copied to clipboard

Lifecycle Events Promise Proposal

Open MarkHerhold opened this issue 10 years ago • 28 comments

I like the concept of the lifecycle events, namely created(), bind(), attached(), detached(), and unbind(). I do think that Aurelia could provide more functionality behind these, especially in regards to waiting on async operations.

Ideally, I would like to be able to implement a hook for the created() callback, return a promise, and have Aurelia wait for it to resolve before invoking the attached() callback. I am not sure what the idea behavior should be if detached() needs to be invoked before the promise from created() resolves, but I imagine the promise would be canceled.

I feel like there is a disconnect between views that have been routed to via the router, as they get the activate() hook which respects and waits for promises, as compared to custom elements which don't respect promises at all.

As an end-user of Aurelia, I would expect to be able to do this:

import { HttpClient } from 'aurelia-fetch-client';

export class Books {
    static inject = [HttpClient];
    constructor(http) {
        this.http = http;
    }

    created() {
        // return a promise that resolves when the data is retrieved
        return this.http.fetch('/books/')
            .then(data => { this.books = data; }); // store the books locally
    }

    // fires only after the promise from `created()` 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
    }
}

I hope this makes sense. I feel like Aurelia is really well thought out, so it wouldn't surprise me if there is already a way to do this.

MarkHerhold avatar Mar 17 '16 22:03 MarkHerhold

We can't provide this across all components. It would be a disaster for performance and would no longer map in any way to web components. If you don't care about web components, you can use the new CompositionTransaction: http://aurelia.io/docs.html#/aurelia/templating/1.0.0-beta.1.1.2/doc/api/class/CompositionTransaction Simply have that injected into your component constructor and then call enlist() this will return you a CompositionTransactionNotifier: http://aurelia.io/docs.html#/aurelia/templating/1.0.0-beta.1.1.2/doc/api/interface/CompositionTransactionNotifier You can call done on that when your async operation is complete. The global composition will wait to attach until after you are done.

EisenbergEffect avatar Mar 17 '16 22:03 EisenbergEffect

This works really well and was exactly what I was after, @EisenbergEffect! You have my thanks.

Here is what @EisenbergEffect said translated into code:

import { HttpClient } from 'aurelia-fetch-client';
import { CompositionTransaction } from 'aurelia-framework';

export class YearToDateGauge {
    static inject = [HttpClient, CompositionTransaction];
    constructor(http, compositionTransaction) {
        this.http = http;

        // https://github.com/aurelia/framework/issues/367
        this.compositionTransactionNotifier = compositionTransaction.enlist();
    }

    created() {
        // retrieve the data
        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 `compositionTransactionNotifier.done()` is called
    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
    }
}

MarkHerhold avatar Mar 17 '16 22:03 MarkHerhold

Great question and answer - I saved this to my offbrain storage: http://blog.williamhayes.org/2016/03/aurelia-custom-element-async-life-cycle.html http://blog.williamhayes.org/2016/03/aurelia-custom-element-async-life-cycle.html

On Mar 17, 2016, at 6:45 PM, Mark Herhold [email protected] wrote:

This works really well and was exactly what I was after, @EisenbergEffect https://github.com/EisenbergEffect! You have my thanks.

Here is what @EisenbergEffect https://github.com/EisenbergEffect said translated into code:

import { HttpClient } from 'aurelia-fetch-client'; import { CompositionTransaction } from 'aurelia-framework';

export class YearToDateGauge { static inject = [HttpClient, CompositionTransaction]; constructor(http, compositionTransaction) { this.http = http;

    // https://github.com/aurelia/framework/issues/367
    this.compositionTransaction = compositionTransaction;
    this.compositionTransactionNotifier = this.compositionTransaction.enlist();
}

created() {
    // return a promise that resolves when the data is retrieved
    return 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 `created()` 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
}

} — You are receiving this because you are subscribed to this thread. Reply to this email directly or view it on GitHub https://github.com/aurelia/framework/issues/367#issuecomment-198113149

wshayes avatar Mar 17 '16 22:03 wshayes

Glad it worked for you! :)

EisenbergEffect avatar Mar 17 '16 23:03 EisenbergEffect

And Dwayne is adding it to his book as well :)

On Mar 17, 2016, at 7:05 PM, Rob Eisenberg [email protected] wrote:

Glad it worked for you! :)

— You are receiving this because you commented. Reply to this email directly or view it on GitHub https://github.com/aurelia/framework/issues/367#issuecomment-198120826

wshayes avatar Mar 17 '16 23:03 wshayes

@MarkHerhold following line from Your example isn't needed as i understand: this.compositionTransaction = compositionTransaction;

atsu85 avatar Mar 18 '16 06:03 atsu85

@atsu85 you are correct. The constructor could be changed to:

    constructor(http, compositionTransaction) {
        this.http = http;

        // https://github.com/aurelia/framework/issues/367
        this.compositionTransactionNotifier = compositionTransaction.enlist();
    }

MarkHerhold avatar Mar 18 '16 12:03 MarkHerhold

@MarkHerhold, one more thing. I guess it doesn't make sense to return a promise from created(), as the framework doesn't do anything with it. So probably there is one more thing You should change: To avoid misunderstanding, You should replace return this.http.fetch('/books/') with this.http.fetch('/books/').

atsu85 avatar Mar 20 '16 06:03 atsu85

@atsu85 Great point! I updated the code block above to reflect both changes discussed.

MarkHerhold avatar Mar 20 '16 17:03 MarkHerhold

@MarkHerhold Does it work equally well if you enlist inside of the bind callback? and kick off the data load during bind?

EisenbergEffect avatar Mar 20 '16 17:03 EisenbergEffect

@EisenbergEffect please disregard my previous commment (deleted)

MarkHerhold avatar Mar 20 '16 18:03 MarkHerhold

@EisenbergEffect Yes is does. :+1:

Here is an equivalent-example of what the code looks like that I tried:

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;
        this.compositionTransactionNotifier = null;
    }

    bind() {
        // enlist
        this.compositionTransactionNotifier = this.compositionTransaction.enlist();

        // retrieve the data
        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 `compositionTransactionNotifier.done()` is called
    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
    }
}

MarkHerhold avatar Mar 20 '16 18:03 MarkHerhold

@EisenbergEffect

@MarkHerhold Does it work equally well if you enlist inside of the bind callback?

what would be the benefit of this approach? The down side of this approach is

  1. simplicity (more code without much difference)
  2. holding references to 2 objects instead of 1 (in fields) so i'd probably only store the compositionTransactionNotifier to the field (in the constructor) if there are no good reasons of doing what You asked about.

atsu85 avatar Mar 20 '16 21:03 atsu85

If you ever wanted to use view caching, the first option 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.

EisenbergEffect avatar Mar 20 '16 21:03 EisenbergEffect

If you ever wanted to use view caching, the first option 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.

Good point, thanks!

atsu85 avatar Mar 21 '16 06:03 atsu85

any suggestion on howto handle a rejected promise here? can i cancel attaching, unbind myself or something?

edit: stupid question. i obviously just display (in the element), whatever i like

doktordirk avatar Mar 27 '16 17:03 doktordirk

You can't cancel those events. You probably want to plan, from a UX perspective for failure and have the component render differently if that happens.

However, my personal recommendation is to not put data access inside of "wdigets" but instead to put that inside "screens" that are controlled by the router. Then you can control navigation if there is a failure. Those screens can then bind the data into the widgets which encapsulate some common rendering.

EisenbergEffect avatar Mar 27 '16 22:03 EisenbergEffect

@EisenbergEffect Can you expand on:

The global composition will wait to attach until after you are done.

Does this mean that if I use this method in any of my custom elements, all of my custom-elements will wait until that one promise resolves?

istrau3 avatar May 06 '16 16:05 istrau3

It means that the the highest level component at the time which is adding nodes to the DOM will wait to add those nodes until after the transaction completes,

A common example is the router. The router processes a navigation and eventually wants to add the dom for the new view into the document. However, if there's a compose element in the new view, it may be asynchronously composing another widget. The router uses the above mechanism to know when the internal composition is complete. When it is, it then adds the view to the document. This allows complex compositions that may be async to result in a single batch modification of the document once all internal async compositions are done.

EisenbergEffect avatar May 06 '16 16:05 EisenbergEffect

@EisenbergEffect the doc location for http://aurelia.io/docs.html#/aurelia/templating/1.0.0-beta.1.1.2/doc/api/interface/CompositionTransactionNotifier appear to have been changed. Can you point me to the right direction?

diefans avatar Jul 26 '16 13:07 diefans