Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ember.js

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.

like image 413
Tadhg McCarthy Avatar asked Nov 27 '22 09:11

Tadhg McCarthy


2 Answers

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.

like image 162
Luke Melia Avatar answered Dec 11 '22 02:12

Luke Melia


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]')
});
like image 32
Panagiotis Panagi Avatar answered Dec 11 '22 02:12

Panagiotis Panagi