Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set attribute of all models in backbone collection

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});
like image 403
sublime Avatar asked Dec 14 '12 22:12

sublime


People also ask

Can we set default values for model in Backbone js?

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.

How can we get the attribute value of a model in Backbone js?

js Get model is used to get the value of an attribute on a model. Syntax: model. get(attribute)

Which of the following is the correct syntax for creating backbone collection with model model?

The Backbone. js collection models specify the array or models which are created inside of a collection. Syntax: collection.


2 Answers

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.

like image 123
machineghost Avatar answered Sep 27 '22 17:09

machineghost


I don’t there is a method for it, but you can try:

collection.forEach(function(model, index) {
    model.set(url, urlArray[index]);
});
like image 20
David Hellsing Avatar answered Sep 27 '22 18:09

David Hellsing