Created
February 11, 2013 08:51
-
-
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.
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
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 @ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How would it be possible to trigger proper events on the collection? Maybe a 'sort' event a view could listen to?