![](/img/trans.png)
[英]How to check if a backbone collection already contains a model with the same idAttribute?
[英]Finding the idAttribute of a collection's model
在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
});
您應該能夠通過模型的原型訪問它:
Model.prototype.idAttribute
或者在您的示例代碼中
var model = coll.get(obj[coll.model.prototype.idAttribute]);
也許我誤解了這個問題,但你不能使用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(); }
});
});
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.