I understand that using pluck method we can get an array of attributes of each model inside a backbone collection
var idsInCollection = collection.pluck('id'); // outputs ["id1","id2"...]
I want to if there is a method that sets up an attribute to each model in the collection,
var urlArray = ["https://url1", "https://url1" ...];
collection.WHAT_IS_THIS_METHOD({"urls": urlArray});
defaults() The Backbone. js defaults model is used to set a default value to a model. It ensures that if a user doesn't specify any data, the model would not fall with empty property.
js Get model is used to get the value of an attribute on a model. Syntax: model. get(attribute)
The Backbone. js collection models specify the array or models which are created inside of a collection. Syntax: collection.
There's not exactly a pre-existing method, but invoke let's you do something similar in a single line:
collection.invoke('set', {"urls": urlArray});
If you wanted to make a re-usable set method on all of your collections, you could do the following:
var YourCollection = Backbone.Collection.extend({
set: function(attributes) {
this.invoke('set', attributes);
// NOTE: This would need to get a little more complex to support the
// set(key, value) syntax
}
});
* EDIT *
Backbone has since added its own set method, and if you overwrite it you'll completely break your Collection. Therefore the above example should really be renamed to setModelAttributes, or anything else which isn't set.
I don’t there is a method for it, but you can try:
collection.forEach(function(model, index) {
model.set(url, urlArray[index]);
});
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