5

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

2 回答 2

6

您可以覆盖“_prepareModel”方法。

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

现在您可以查看在“初始化”中传递给模型的属性,您将获得 some_imp_value,然后您可以在模型上适当设置它。

于 2012-07-02T16:59:10.387 回答
0

虽然它似乎没有记录,但我发现至少在最新版本的骨干网(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"});

注意:我不确定选项对象是否传递给后续的 Collection.add 事件

于 2016-10-27T15:29:39.087 回答