Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EmberJS View - detect if all children views have been rendered

Scenario:

  • Collection of notes (async-loaded) is rendered
  • Two views: NoteView that represents list of notes and NoteOnListView that represents single note
  • I have to run some code (masonry.js) to lay them, but it requires all notes to be rendered first, it needs to know count and properties of those children

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?

like image 369
pipboy3k Avatar asked Dec 15 '22 11:12

pipboy3k


1 Answers

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.

like image 60
Ethan Selzer Avatar answered Dec 27 '22 19:12

Ethan Selzer