-
Notifications
You must be signed in to change notification settings - Fork 0
Adding support for sorted collections
Support for sorted collections in a CollectionView
and CompositeView
is not directly included with Marionette. There are a number of scenarios that make this difficult to do, with the current code. For a complete discussion on this, see ticket #134.
With v0.9.0 of Marionette, though, a third parameter was added to the appendHtml
method call for the Collection and Composite view types: index
appendHtml: function(cv, iv, index){
// ...
},
The inclusion of this parameter should allow you to add support for sorted collections, within your specific views that need it. One example implementation may look like this:
MySortedView = Backbone.Marionette.CollectionView.extend({
// ...,
appendHtml: function(collectionView, itemView, index){
var childrenContainer = $(collectionView.childrenContainer || collectionView.el);
var children = childrenContainer.children();
if (children.size() === index) {
childrenContainer.append(itemView.el);
} else {
childrenContainer.children().eq(index).before(itemView.el);
}
}
});
This implementation will check to see if the current index is the same as the number of children already appended, and do a simple append if it is. That way the first rendering is simple appends, and very fast. Subsequent adds will find the correct position in the DOM to insert the item view.
You can apply this code to any CollectionView
or CompositeView
as needed. In a CompositeView, though, you will have the additional requirement of selecting the correct container for the collection. For more information on that, see the CompositeView documentation.