4

设想:

  • 呈现笔记集合(异步加载)
  • 两个视图:表示笔记列表的 NoteView 和表示单个笔记的 NoteOnListView
  • 我必须运行一些代码(masonry.js)来放置它们,但它需要首先呈现所有笔记,它需要知道这些孩子的数量和属性

我有一个模板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 等到它的所有孩子都被渲染?

4

1 回答 1

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!     
    }
} );

这是一个在 Ember 1.0 RC2 中演示此技术的示例。

有关 Ember.run.scheduleOnce 的更多信息,请参阅文档

于 2013-04-21T01:52:42.403 回答