Backbone.js collections, get the next/previous model

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!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s