Skip to content

Instantly share code, notes, and snippets.

@coderek
Created July 25, 2014 01:55
Show Gist options
  • Save coderek/311884222a861bd08c73 to your computer and use it in GitHub Desktop.
Save coderek/311884222a861bd08c73 to your computer and use it in GitHub Desktop.
add view sorting to marionette collection view version < 2.0
d = [{a: 34}, {a: 32}, {a: 7}]
Item = Marionette.ItemView.extend
template: _.template "<%= a %>"
c = new Backbone.Collection(d)
CV = Marionette.CollectionView.extend
removeItemView: (item)->
view = @children.findByModel(item)
@removeChildView(view)
@checkEmpty()
@_updateIndices(view, false)
addItemView: (item, ItemView, index)->
itemViewOptions = Marionette.getOption(@, 'itemViewOptions')
if _.isFunction(itemViewOptions)
itemViewOptions = itemViewOptions.call(@, item, index)
view = @buildItemView(item, ItemView, itemViewOptions)
@addChildViewEventForwarding(view)
@triggerMethod("before:item:added", view)
@_updateIndices(view, true, index)
@children.add(view)
@renderItemView(view, index)
if @_isShown and not @isBuffering
Marionette.triggerMethod.call(view, "show")
@triggerMethod("after:item:added", view)
view
appendHtml: (collectionView, itemView, index)->
if collectionView.isBuffering
collectionView.elBuffer.appendChild(itemView.el)
collectionView._bufferedChildren.push(itemView)
else
currentView = @children.find (view)-> view._index is index + 1
if currentView
currentView.$el.before(itemView.el)
else
@$el.append itemView.el
_updateIndices: (view, increment, index)->
if increment
view._index = index
@children.each (laterView)->
laterView._index = laterView._index + 1 if laterView._index >= view._index
else
@children.each (laterView)->
laterView._index = laterView._index - 1 if laterView._index >= view._index
_sortViews: ()->
orderChanged = @collection.find (item, index)->
view = @children.findByModel(item)
return view and view._index isnt index
, @
@render() if orderChanged
v = new CV({collection: c, itemView: Item})
c.comparator = (m)-> m.get('a')
v.render()
v.listenTo c, 'sort', v._sortViews
$('body').append(v.el)
c.add({a: 120}, {at: 0})
c.push({a: 100})
c.push({a: 250})
console.log JSON.stringify(c.toJSON())
c.remove(c.at(1))
console.log JSON.stringify(c.toJSON())
c.add({a: 124}, {at: 1})
console.log JSON.stringify(c.toJSON())
c.sort()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment