pipboy3k
pipboy3k

Reputation: 123

EmberJS View - detect if all children views have been rendered

Scenario:

I have a template, notes.hjs:

{{#each note in controller}}
    {{view App.NoteOnListView}}
{{/each}}

And views:

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

Console output:

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!

I have some possible solutions to this problem, but all of them look hacky. Is there a nice way I can tell NotesView to wait until all its children are rendered?

Upvotes: 4

Views: 2521

Answers (1)

Ethan Selzer
Ethan Selzer

Reputation: 1755

If you change your strategy to subclassing Ember.CollectionView you could use the following approach to receiving notification that your child views have finished rendering.

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

Here is an example that demonstrates this technique in Ember 1.0 RC2.

For more information on Ember.run.scheduleOnce see the docs.

Upvotes: 12

Related Questions