在集合的上下文中,我想检索基于某些包含模型数据的对象的模型实例,但我不想对 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
});