I’m using Backbone.js for my project lickcreator. I really love Backbone.js, especially the collections stuff is just awesome. I was looking for an easy way to get to the next model in a collection , but couldn’t find it. Of course, you can iterate over the collection and get to the model you want, but that seems awkward.
Here’s what I came up with. Given a model as an argument, return the next model (or previous model) in the collection. Please note there’s no error handling for this simple example.
var NotesCollection = Backbone.Collection.extend({ model: Note, next_model: function(n) { return this.at(this.indexOf(n) + 1); }, prev_model: function(n) { return this.at(this.indexOf(n) - 1); } });
Easy peasy! Yay for Backbone!