Skip to content

Instantly share code, notes, and snippets.

@filipmares
Last active November 17, 2018 10:13
Show Gist options
  • Save filipmares/7556159 to your computer and use it in GitHub Desktop.
Save filipmares/7556159 to your computer and use it in GitHub Desktop.
Backbone.Marionette CollectionViews are awesome, but they don't support collection re-ordering out of the box. The library provides some documentation to order CollectionViews and CompositeViews, but it's based on the children already inserted. I prefer my views to reflect the state of my models and collections.

Backbone.Marionette CollectionViews are awesome, but they don't support collection re-ordering out of the box. The library provides some documentation to order CollectionViews and CompositeViews, but it's based on the children already inserted. I prefer my views to reflect the state of my models and collections.

'use strict';
Marionette.SortedCollectionView = Marionette.CollectionView.extend({
/**
* Given a model, function tries to find the correct itemView based on the
* model's cid. Returns itemview or null
* @param model
* @return itemView/null
*/
getItemViewByModel: function(model) {
var viewId;
if (model) {
viewId = this.children._indexByModel[model.cid];
return viewId ? this.children._views[viewId] : null;
} else {
return null;
}
},
/**
* The default implementation of 'appendHtml' but overriden in order to have ordered visual track items.
* @param collectionView
* @param itemView
* @param index
*/
appendHtml: function(collectionView, itemView, index) {
var childrenContainer = collectionView.itemViewContainer ? collectionView.$(collectionView.itemViewContainer) : collectionView.$el,
collection = collectionView.collection,
previousModel, previousView;
// If the index of the model is at the end of the collection append, else insert at proper index
if (index >= collection.size() - 1) {
childrenContainer.append(itemView.el);
} else {
previousModel = collection.at(index + 1);
previousView = this.getItemViewByModel(previousModel);
previousView.$el.before(itemView.$el);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment