我知道我们可以根据属性
在集合中找到所有模型var friends = new Backbone.Collection([
{name: "Athos", job: "Musketeer"},
{name: "Porthos", job: "Musketeer"},
{name: "Aramis", job: "Musketeer"},
{name: "d'Artagnan"},
]);
friends.where({job: "Musketeer"});
但是我想找到没有属性或键的模型。怎么做? 像
这样的东西friends.where(not(job));
非常感谢任何帮助
答案 0 :(得分:2)
我会尝试这样的事情,成为朋友的骨干系列。
function isMusketeer() {
return friend.get('job') && friend.get('job') === "Musketeer";
}
function hasNoJob() {
return !friend.get('job');
}
friends.find(hasNoJob); //The first without a job
friends.find(isMusketeer); //The first that is a musketeer
friends.filter(hasNoJob); // List of results that has no job
friends.filter(isMusketeer); // List of results that are musketeer
我只是将条件/谓词分开,然后应用于您需要的集合下划线功能,在这种情况下,可以根据您的需要获得许多结果或一个结果。
答案 1 :(得分:2)
Backbone为Backbone.Collection
个实例提供wide range of underscore methods。其中一种方法是Backbone.Collection.filter
,它根据自定义函数的结果过滤集合中的模型。以下是如何使用它的示例:
var friends = new Backbone.Collection([
{name: "Athos", job: "Musketeer"},
{name: "Porthos", job: "Musketeer"},
{name: "Aramis", job: "Musketeer"},
{name: "d'Artagnan"},
]);
friends.filter(function(model) {
return _.isUndefined(model.get('job'));
});
上面代码的JSFiddle:https://jsfiddle.net/Ljve5104/