mpneuried
2/11/2013 - 8:51 AM

Backbone code to move a model inside a collection after another model or to the top of the collection.

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 @