Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Marionette.js Event that fires after all items in a CollectionView are rendered?

In Backbone.Marionette.js CollectionViews and CompositeViews, the onDomRefresh event fires when the DOM is initially rendered and ALSO any time that an item is added to the view's collection (this contributes to the dynamic / "live" nature of the views). In my case, I want to run a certain jQuery function, but due to the typical length of the collection, it would be better to only call this function once at the last render to prevent excess function calls to something I only want to do once after all models are rendered in the UI.

Is there a Marionette event with the appropriate timing for this use case?

like image 306
Brian Avatar asked Oct 21 '13 21:10

Brian


2 Answers

I had been trying to use Erik's solution all afternoon but the "collection:rendered" event is never fired. After trawling though the source I see it does not exist anymore :(

But there is a rather easy way to get the behaviour desired.

From within a CollectionView use the onAddChild callback to do the following:

onAddChild : function() {
// Check all the models in the collection have their child views rendered
  if ( this.children.length == this.collection.length ) {
    // Now you could do something like
    this.trigger("collection:rendered");
  }
}

It works because the collection count goes up to its new length instantly while the children length is updated one at a time.

Pretty simple, it has made me happy :) Hope it helps someone else too.

like image 176
mexitalian Avatar answered Sep 30 '22 21:09

mexitalian


You can listen to "collection:rendered". Here is what the CollectionView triggers when it is done rendering children:

this.triggerMethod("collection:rendered", this);

You can use this:

this.listenTo(myCollectionView, "collection:rendered", _awesomeCallback);

Of course you will need to change the above.

EDIT:

Here is the render method for a collection view:

render: function(){
    this.isClosed = false;
    this.triggerBeforeRender();
    this._renderChildren();
    this.triggerRendered();
    return this;
  }

this.triggerRendered() fires off this.triggerMethod("collection:rendered", this), so the collection will be rendered before "collection:rendered" is triggered.

like image 39
Erik Ahlswede Avatar answered Sep 30 '22 19:09

Erik Ahlswede