set attribute of all models in backbone collection

sublime picture sublime · Dec 14, 2012 · Viewed 19.2k times · Source

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});

Answer

machineghost picture machineghost · Dec 14, 2012

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.