在集合的上下文中,我想根据包含模型数据的某些对象检索模型实例,但我不想对 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
});
最佳答案
您应该能够通过模型的原型(prototype)访问它:
Model.prototype.idAttribute
或者在你的示例代码中
var model = coll.get(obj[coll.model.prototype.idAttribute]);
关于javascript - 查找集合模型的 idAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13916554/