在Collection的上下文中,我想基于包含模型数据的某个对象来检索模型实例,但我不想对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
});
答案 0 :(得分:3)
您应该可以通过模型的原型访问它:
Model.prototype.idAttribute
或在您的示例代码中
var model = coll.get(obj[coll.model.prototype.idAttribute]);
答案 1 :(得分:0)
也许我误解了这个问题,但你不能使用Collection.where()
方法吗?
来自Backbone文档:
其中
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(); }
});
});
}
});