Joe
Joe

Reputation: 8042

Getting the next and previous elements in backbone.js

Let's say I have a collection in backbone and I want to be able to find the previous and next elements for a given element. Please assume that elements can be dynamically deleted and added.

var MyModel=Backbone.Model.extend({
 nextElement: function(){
//????
},
previousElement:function(){
//?????
}
});

var MyCollectionType=Backbone.Collection.extend({
model:MyModel;
});
var collection=new MyCollectionType

Upvotes: 1

Views: 2147

Answers (2)

azibi
azibi

Reputation: 4397

It was discussed as a backbone issue

https://github.com/jashkenas/backbone/issues/136

linssen

It can be something like this You can always get around this using a new model method:

getRelative: function(direction) {
    return this.collection.at(this.collection.indexOf(this) + direction);
}

So if you pass -1 it'll get the previous and 1 will get you the next. It'll return -1 if it doesn't find anything.

Upvotes: 0

Paul
Paul

Reputation: 18597

When a model is added to a collection, the collection property is added to the model which references the collection it is in. You can use this property in the nextElement and previousElement methods.

var MyModel = Backbone.Model.extend({
  initialize: function() {
    _.bindAll(this, 'nextElement', 'previousElement');
  },

  nextElement: function() {
    var index = this.collection.indexOf(this);
    if ((index + 1) === this.collection.length) {
      //It's the last model in the collection so return null
      return null;
    }
    return this.collection.at(index + 1);
  },

  previousElement: function() {
    var index = this.collection.indexOf(this);
    if (index === 0 ) {
      //It's the first element in the collection so return null
      return null;
    }
    return this.collection.at(index - 1);
  }
}

However, it seems that nextElement and previousElement are concerns the collection should have and not the model. Have you considered putting these functions on the collection rather than the model?

Upvotes: 13

Related Questions