1

バックボーンにコレクションがあり、特定の要素の前の要素と次の要素を見つけたいとしましょう。要素は動的に削除および追加できると想定してください。

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

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

2 に答える 2

13

モデルがコレクションに追加されると、そのcollectionプロパティが含まれるコレクションを参照するモデルにプロパティが追加されます。このプロパティは、nextElement および previousElement メソッドで使用できます。

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);
  }
}

ただし、モデルではなく、コレクションが持つべき懸念があるようnextElementですpreviousElement。これらの関数をモデルではなくコレクションに配置することを検討しましたか?

于 2012-04-09T21:23:22.580 に答える
0

バックボーン問題として議論された

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

リンセン

これは次のようなものです。これは、新しいモデル メソッドを使用していつでも回避できます。

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

したがって、-1 を渡すと前のものを取得し、1 を渡すと次のものを取得します。何も見つからない場合は -1 を返します。

于 2015-06-02T20:47:53.450 に答える