Skip to content

Instantly share code, notes, and snippets.

@mpneuried
Created February 11, 2013 08:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpneuried/4753344 to your computer and use it in GitHub Desktop.
Save mpneuried/4753344 to your computer and use it in GitHub Desktop.
Backbone code to move a model inside a collection after another model or to the top of the collection.
class SortableCollection extends Collection
###
## moveAfter
`collections.moveAfter( model, predecessor )`
Move a model after another model or if `predecessor` is `null` or `0` to the top of the model list
@param { Model | String | Number } model The model to move, it's `id` or the `cid`
@param { Function } predecessor The predecessor model to move the model behind or it's `id` or `cid`
@return { Self } Return the collection for chanining
@api public
###
moveAfter: ( model, predecessor )=>
# get the model
_m = @get( model )
# if not found abort
if not _m?
return @
# get the current index and remove it from the collection
idx = @indexOf( _m )
@models.splice( idx,1 )
# get the predecessor index
_mPred = @get( predecessor )
idxPred = @indexOf( _mPred )
# put back the model after the predecessor or if not found to the top
@models.splice( idxPred+1,0,_m )
# return self for chaining
return @
@bendulum
Copy link

How would it be possible to trigger proper events on the collection? Maybe a 'sort' event a view could listen to?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment