This is taken from the Backbone.js documentation:
var musketeers = friends.where({job: "Musketeer"});
Where you can get an array of models where job is equal is "Musketeer". But how do I do the opposite? How can I get an array of models where job is anything else but "Musketeer"?
Backbone.js model.get() The Backbone.js Get model is used to get the value of an attribute on a model. Syntax: attributes: It defines property of a created model. Let's take an example. See this example: Output: Save the above code in get.html file and open this file in a new browser.
BackboneJS - Collection. Collections are ordered sets of Models. We just need to extend the backbone's collection class to create our own collection. Any event that is triggered on a model in a collection will also be triggered on the collection directly. This allows you to listen for changes to specific attributes in any model in a collection.
All the Backbone.JS Collection’ methods are listed below: To extend the backbone’s collection class to create own collection. To specify the model class. To create a model instance. To specify the array of models which are created inside of the collection.
Here’s a little excerpt from the Backbone docs on models: Models are the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control. With that in mind, let’s draft up a little example that we’ll use going forward.
I don't know of something that's a direct opposite, but you can use a filter to the same effect.
var notMusketeers = friends.filter(function (friend) {
return friend.job !== 'Musketeer';
});
If you're using filter
directly on a Backbone collection, you must use it this way:
var notMusketeers = friends.filter(function(model){
return model.get('job') !== 'Musketeer';
});
Then notMusketeers
will be an array of Backbone model instances.
If friends
is just an array of objects (standard collection), you could use the underscore filter
this way:
var notMusketeers = _.filter(friends, function(obj){
return obj.job !== 'Musketeer';
});
If ES6+ features are available to you, const
, destructuring and arrow functions could make it a little less verbose:
const notMusketeers = friends.filter(({ job }) => job !== 'Musketeer');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With