Tadhg McCarthy
Tadhg McCarthy

Reputation: 95

Emberjs - How to wait until a template is fully rendered before accessing its children

Is there a way to wait until a template is fully rendered before accessing its children through a view, using jquery for instance?

didInsertElement doesn't seem to work as expected for me. I need to add an additional half second delay before the template is fully constructed. The template iterates over an array in the controller and creates several divs. it's these divs that aren't accessible immediately, even when I override didInsertElement.

Upvotes: 4

Views: 5147

Answers (2)

Luke Melia
Luke Melia

Reputation: 8389

I recently added something to Ember that will do this more elegantly: an afterRender queue. See this commit, in particular the test for an example of usage.

Upvotes: 16

Panagiotis Panagi
Panagiotis Panagi

Reputation: 10077

I'm not aware of how you insert those childViews, but one way to do it, is as follows:

didInsertElement: function(){
  if (this.$().find(".myAwesomeChildViews").length > 0) {  // <-- adapt this to your needs
     // my childViews are inserted
  } else {
     Ember.run.next(this, function() {
        this.didInsertElement();
     });
  }
}

The important thing here is that didInsertElement() will keep being called until the check evaluates to true.


Even better, you can refactor it as follows:

Ember.View.reopen({
    didInsertElement: function() {
        this._super();
        this.setIsRendered();
    },

     setIsRendered: function() {
        if (!!this.$()) {
            this.set('isRendered', true);
        } else {
            Ember.run.next(this, function() {
                this.setIsRendered();
            });
        }
    },
});

And then in your view:

App.MyView = Ember.View.extend({
   areMyChildViewsRendered: function() {
      return this.get('childViews').everyProperty('isRendered');
   }.property('[email protected]')
});

Upvotes: 14

Related Questions