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

≡放荡痞女 提交于 2020-01-01 06:08:06

问题


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.


回答1:


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('chilViews.@each.isRendered')
});



回答2:


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.



来源:https://stackoverflow.com/questions/12086848/emberjs-how-to-wait-until-a-template-is-fully-rendered-before-accessing-its-ch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!