3

I know that we can find all models in collection like so, based on attributes

var friends = new Backbone.Collection([
              {name: "Athos",      job: "Musketeer"},
              {name: "Porthos",    job: "Musketeer"},
              {name: "Aramis",     job: "Musketeer"},
              {name: "d'Artagnan"},
            ]);
friends.where({job: "Musketeer"});

However i want to find the model which doesn have the attribute, or the key. How to do it? Something like

friends.where(not(job));

Any help is greatly appreciated

prajnavantha
  • 1,111
  • 13
  • 17

2 Answers2

2

I would try something like this, being friends a backbone collection.

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

I just separate the criteria / predicates , and then applied to the collections underscore function you need, in this case can be for many results or one result, depending on your needs.

juan garcia
  • 1,326
  • 2
  • 23
  • 56
2

Backbone provide wide range of underscore methods for Backbone.Collection instances. One of such method is Backbone.Collection.filter which filters models in collection based on the result of a custom function. Here is an example of how it could be used:

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 for the code above: https://jsfiddle.net/Ljve5104/

Dmitriy Simushev
  • 308
  • 1
  • 16