最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting the next and previous elements in backbone.js - Stack Overflow

programmeradmin0浏览0评论

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

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
Share Improve this question edited Apr 9, 2012 at 20:51 jwueller 31k5 gold badges67 silver badges70 bronze badges asked Apr 9, 2012 at 20:45 JoeJoe 8,04218 gold badges57 silver badges86 bronze badges 2
  • 3 Shouldn't you be asking the collection for the information? – mu is too short Commented Apr 9, 2012 at 21:07
  • It would probably better to put it on the collection. But if you are writing something small, it can go either way. – Joe Commented Apr 10, 2012 at 3:55
Add a ment  | 

2 Answers 2

Reset to default 13

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?

It was discussed as a backbone issue

https://github./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.

发布评论

评论列表(0)

  1. 暂无评论