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.
Last active
November 17, 2018 10:13
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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