Is there a way to get a callback when Ember.js has finished loading everything?

10,137

Solution 1

There are also several functions defined on Views that can be overloaded and which will be called automatically. These include willInsertElement(), didInsertElement(), afterRender(), etc.

In particular I find didInsertElement() a useful time to run code that in a regular object-oriented system would be run in the constructor.

Solution 2

You can use the ready property of Ember.Application.

example from http://awardwinningfjords.com/2011/12/27/emberjs-collections.html:

// Setup a global namespace for our code.
Twitter = Em.Application.create({

  // When everything is loaded.
  ready: function() {

    // Start polling Twitter
    setInterval(function() {
      Twitter.searchResults.refresh();
    }, 2000);

    // The default search is empty, let's find some cats.
    Twitter.searchResults.set("query", "cats");

    // Call the superclass's `ready` method.
    this._super();
  }
});

Solution 3

LazyBoy's answer is what you want to do, but it will work differently than you think. The phrasing of your question highlights an interesting point about Ember.

In your question you specified that you wanted a callback after the views were rendered. However, for good 'Ember' style, you should use the 'ready' callback which fires after the application is initialized, but before the views are rendered.

The important conceptual point is that after the callback updates the data-model you should then let Ember update the views.

Letting ember update the view is mostly straightforward. There are some edge cases where it's necessary to use 'didFoo' callbacks to avoid state-transition flickers in the view. (E.g., avoid showing "no items found" for 0.2 seconds.)

If that doesn't work for you, you might also investigate the 'onLoad' callback.

Solution 4

You can use jQuery ajax callbacks for this:

$(document).ajaxStart(function(){ console.log("ajax started")})
$(document).ajaxStop(function(){ console.log("ajax stopped")})

This will work for all ajax requests.

Solution 5

I simply put this into the Application Route

actions: {
    loading: function(transition, route) {

        this.controllerFor('application').set('isLoading', true);

        this.router.on('didTransition', this, function(){
          this.controllerFor('application').set('isLoading', false);
        });
    }
}

And then anywhere in my template I can enable and disable loading stuff using {{#if isLoading}} or I can add special jQuery events inside the actual loading action.

Very simple but effective.

Share:
10,137
jede
Author by

jede

Updated on July 06, 2022

Comments

  • jede
    jede almost 2 years

    I am building an Ember.js app and I need to do some additional setup after everything is rendered/loaded.

    Is there a way to get such a callback? Thanks!