Skip to content

Instantly share code, notes, and snippets.

@rjz
Created November 21, 2012 01:01
Show Gist options
  • Save rjz/4122378 to your computer and use it in GitHub Desktop.
Save rjz/4122378 to your computer and use it in GitHub Desktop.
Find next model in a Backbone Collection
# Methods for cycling through the models in a Backbone Collection
# Usage:
#
# c = new MyCollection([...])
# nextModel = c.modelAfter(myModel)
# myModel == c.modelBefore(nextModel)
# # true
#
class MyCollection extends Backbone.Collection
# ...
# Find previous model in the collection
# move to end if we're off the start of the array
modelBefore: (model) ->
index = @indexOf(model) - 1
index = @.length - 1 if index < 0
@at(index)
# Find next model in the collection
# start over if we're off the end of the array
modelAfter: (model) ->
index = @indexOf(model) + 1
index = 0 if index == @.length
@at(index)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment