查找Backbone集合中没有属性的模型

时间:2016-01-22 12:57:17

标签: javascript backbone.js collections backbone-collections backbone-model

我知道我们可以根据属性

在集合中找到所有模型
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));

非常感谢任何帮助

2 个答案:

答案 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/