有人可以在Backbone中向我解释范围吗?以下示例中的最佳方法是使用get方法检索默认变量的值吗?

如果我不使用get方法,则我的数组显示为未定义。

App.Models.Site = Backbone.Model.extend({
    defaults: {
        testArray: [1, 2, 3]
    },

    initialize: function(){
        console.log('initialize', this.testArray); // logs undefined
        console.log('initialize', this.get('testArray')); // logs [1, 2, 3]

        this.test();
    },

    test: function(){
        console.log('initialize', this.testArray); // logs undefined
        console.log('test', this.get('testArray')); // logs [1, 2, 3]
    }
});

最佳答案

您可以使用defaults访问App.Models.Site.prototype.defaults值。

如果使用get(请参见下文),则将检索模型实例的当前testArray值。在各个实例之间,这并不总是相同的。



模型属性存储在模型的.attributes属性内,而不是模型本身。检索模型属性值的唯一方法是使用get(propertyName)

之所以这样做是因为set不仅会更改对象的值,还会触发事件以使用新值更新UI等。如果可以使用this.testArray代替this.get('testArray')您还可以为this.testArray分配值是合理的-但这会破坏事情。

因此,您也不应使用.attributes分配值-不会触发任何事件处理程序。

09-30 16:11
查看更多