如何检查 Backbone.js 集合是否已经包含具有相同idAttribute的模型?

ylamdve6  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(158)

我的 Backbone.js 模型的idAttribute可以是任何值( Backbone.js 的默认值是“id”)。我希望在将模型插入到 Backbone.js 集合之前检查该集合是否已经包含具有相同idAttribute值的模型。
myCollection.contains(myNewModel)总是返回false。我猜这是因为候选模型不一定是集合中已经存在的同一个示例。
我试过了

idAttribute: string = myColllection.model.prototype.idAttribute; // Works fine
let id: string = itemToInsert.get(idAttribute); // Works fine
let exists : boolean : myCollection.findWhere({ idAttribute : id }); // Undefined!

我想要像这样的东西

let test: boolean = _.any(self.collection, item => idAttributeValue === item.get("idAttribute")).value();

但我不确定确切的语法。

to94eoyn

to94eoyn1#

您可以使用Collection.get来判断集合中是否有具有指定id的模型,而不论基础idAttribute为何。
例如,
第一个
如果要使用findWhere,则必须使用square bracket notation作为属性的散列:

var finder = [];
var idAttribute = M.prototype.idAttribute;
finder[idAttribute] = 1;
console.log(c.findWhere(finder));

相关问题