Backbone.js: Passing a value from a collection to each model

I need to pass a value from the view of each model inside the collection during initialization.

We can pass the Till Collection using "options" in the Backbone.Collection constructor.

After that, is there any technique in which I can pass some “options” to each model within the collection?

var Song = Backbone.Model.extend({
    defaults: {
        name: "Not specified",
        artist: "Not specified"
    },
    initialize: function (attributes, options) {
        //Need the some_imp_value accessible here
    },
});

var Album = Backbone.Collection.extend({
    model: Song

    initialize: function (models, options) {
        this.some_imp_value = option.some_imp_value;
    }
});
+5
source share
2 answers

You can override the "_prepareModel" method.

var Album = Backbone.Collection.extend({
    model: Song

    initialize: function (models, options) {
        this.some_imp_value = option.some_imp_value;
    },

    _prepareModel: function (model, options) {
        if (!(model instanceof Song)) {
          model.some_imp_value = this.some_imp_value;
        }
        return Backbone.Collection.prototype._prepareModel.call(this, model, options);
    }
});

Now you can look at the attributes passed to the model in "initialize" and you will get some_imp_value, which can then be set on the model as needed.

+6
source

, , , , , (v1.3.3) , , , , . , , .

:

var Song = Backbone.Model.extend({
    defaults: {
        name: "Not specified",
        artist: "Not specified"
    },
    initialize: function (attributes, options) {
        //passed through options
        this.some_imp_value = options.some_imp_value

        //accessing parent collection assigned attributes
        this.some_other_value = this.collection.some_other_value
    },
});

var Album = Backbone.Collection.extend({
    model: Song

    initialize: function (models, options) {
        this.some_other_value = "some other value!";
    }
});

var myAlbum = new Album([array,of,models],{some_imp_value:"THIS IS THE VALUE"});

. , options Collection.add

0

All Articles