1

在集合的上下文中,我想检索基于某些包含模型数据的对象的模型实例,但我不想对 idAttribute 进行硬编码。

当您已经有一个模型实例时,Backbone 使事情变得容易,您可以访问它的.id属性并将其整理出来,但我似乎找不到另一种方式,除了创建模型实例只是为了得到它idAttribute

例如:

var Cat = Backbone.Model.extend({
  defaults: {
    name: '',
    age: null
  },

  idAttribute: 'name'
});

var PushCollection = Backbone.Collection.extend({
  initialize: function () {
    coll = this;
    somePushConnection.on('deleted', function (deleted) {
      _.each(deleted, function (obj) {
        // obj being something like: {name: 'mittens', age: 302}
        var model = coll.get(obj[coll.model.idAttribute]); // Can't do this!
        if (model) { model.destroy(); }
      });
    });
  }
});

var Cats = PushCollection.extend({
  model: Cat
});
4

2 回答 2

3

您应该能够通过模型的原型访问它:

Model.prototype.idAttribute

或在您的示例代码中

var model = coll.get(obj[coll.model.prototype.idAttribute]);
于 2012-12-17T15:04:18.670 回答
0

也许我误解了这个问题,但是您不能使用该Collection.where()方法吗?

从骨干文档:

在哪里 collection.where(attributes)

返回集合中与传递的属性匹配的所有模型的数组。对于过滤器的简单情况很有用。

var friends = new Backbone.Collection([
  {name: "Athos",      job: "Musketeer"},
  {name: "Porthos",    job: "Musketeer"},
  {name: "Aramis",     job: "Musketeer"},
  {name: "d'Artagnan", job: "Guard"},
]);

var musketeers = friends.where({job: "Musketeer"});

alert(musketeers.length);

因此,在您的示例代码中:

var PushCollection = Backbone.Collection.extend({
  initialize: function () {
    coll = this;
    somePushConnection.on('deleted', function (deleted) {
      _.each(deleted, function (obj) {
        // obj being something like: {name: 'mittens', age: 302}
        var model = coll.where(obj);
        if (model) { model.destroy(); }
      });
    });
  }
});
于 2012-12-19T20:29:03.510 回答