简体   繁体   中英

Backbone.js: Passing value From Collection to each model

I need to pass a value from the view to each models inside a collection, while initializing.

Till Collection we can pass with 'options' in the Backbone.Collection constructor.

After this, is there any technique where I can pass the some 'options' into each models inside 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;
    }
});

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'll get some_imp_value, which you can then set on the model as appropriate..

While it appears to be undocumented, I have found that in at least the latest version of backbone (v1.3.3) that the options object passed to a collection gets passed to each child model, extended into the other option items generated by the collection. I haven't spent the time to confirm if this is the case with older releases.

Example:

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

Note: I am unsure if the options object is passed to subsequent Collection.add events

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM