Skip to content

Instantly share code, notes, and snippets.

@iamjwc
Created March 9, 2011 04:14
Show Gist options
  • Save iamjwc/861684 to your computer and use it in GitHub Desktop.
Save iamjwc/861684 to your computer and use it in GitHub Desktop.
Move =
move: (modelOrIndex, endIndex) ->
if typeof modelOrIndex == "number"
this.__moveIndexTo__(modelOrIndex, endIndex)
else
this.__moveModelTo__(modelOrIndex, endIndex)
__moveModelTo__: (model, endIndex) ->
this.__moveIndexTo__ _.indexOf(this.models, model), endIndex
__moveIndexTo__: (startIndex, endIndex) ->
movedUp = startIndex > endIndex
movedDown = startIndex < endIndex
_.each this.models, (model, i) ->
model._index = if i == startIndex
endIndex
else if movedDown && i <= endIndex
i - 1
else if movedUp && i >= endIndex
i + 1
else
i
# Save old comparator
c = this.comparator
# Build comparator on _index just set
# and sort on this index.
this.comparator = (model) -> model._index
this.sort()
# Return comparator to old value
this.comparator = c
_.extend Backbone.Collection.prototype, Move
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment