情景:
我有一个模板 notes.hjs :
{{#each note in controller}}
{{view App.NoteOnListView}}
{{/each}}
观点:
App.NotesView = Ember.View.extend({
didInsertElement: function() {
console.log('the list has been rendered');
}
});
App.NoteOnListView = Ember.View.extend({
didInsertElement: function() {
console.log('a note has been inserted');
},
afterRender: function() {
console.log('a note has been rendered');
}
});
控制台输出:
the list has been rendered
XHR finished loading: "http://localhost:3000/notes"
a note has been rendered
a note has been inserted
a note has been rendered
a note has been inserted
// ...
a note has been rendered
a note has been inserted
// This is where I need to run code!
我有一些可能的解决方案来解决这个问题,但所有这些解决方案看起来都很糟糕。有没有一种很好的方法可以告诉NotesView等待它的所有子项都被渲染?
答案 0 :(得分:12)
如果您将策略更改为继承Ember.CollectionView,则可以使用以下方法接收子视图已完成呈现的通知。
App.CV = Ember.CollectionView.extend( {
itemViewClass : Ember.View.extend( {
templateName : 'item'
} ),
onChildViewsChanged : function( obj, key ){
var length = this.get( 'childViews.length' );
if( length > 0 ){
Ember.run.scheduleOnce( 'afterRender', this, 'childViewsDidRender' );
}
}.observes( 'childViews' ),
childViewsDidRender : function(){
//child views have finished rendering!
}
} );
这是一个example,在Ember 1.0 RC2中展示了这项技术。
有关Ember.run.scheduleOnce的更多信息,请参阅docs。