Backbone.js:将值从Collection传递给每个模型

时间:2012-07-02 16:30:06

标签: javascript backbone.js backbone-relational

我需要在初始化时将视图中的值传递给集合中的每个模型。

Till Collection我们可以通过'选项'在Backbone.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;
    }
});

2 个答案:

答案 0 :(得分: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);
    }
});

现在您可以查看在'initialize'中传递给模型的属性,然后您将获得some_imp_value,然后您可以根据需要在模型上设置..

答案 1 :(得分:0)

虽然它似乎没有文档,但我发现至少在最新版本的backbone(v1.3.3)中,传递给集合的options对象被传递给每个子模型,扩展到由其生成的其他选项中集合。我还没有花时间确认旧版本是否属于这种情况。

示例:

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事件