0

我需要使用一些自己的成员来扩展主要的主干功能(视图、模型、路由器)。但是,以下内容无法正常工作:

Backbone.View.prototype.foo = ["bar"];

诚然,表达

testView = new Backbone.view.extend({})
testView2 = new Backbone.view.extend({})
alert(testView.foo.length);

状态 1 但设置

testView2.foo.push("blah");

还将字符串添加到 testView.foo 因为引用是相同的。

任何人都知道如何扩展这些对象?

提前致谢 :)

狮子座

4

1 回答 1

4

通常您不会扩展标准视图,而是创建自己的基本视图类型。您应该避免更改 Backbone 原型上的值。

var BaseView = Backbone.View.extend({
  foo: null,
  initialize: function(options){
    this.foo = ["bar"];

    Backbone.View.prototype.initialize.apply(this, arguments);
  }
});

var testView = new BaseView();
var testView2 = new BaseView();
console.log(testView.foo.length); // prints '1'
console.log(testView2.foo.length); // prints '1'    

testView2.foo.push("blah");

console.log(testView.foo.length); // prints '1'
console.log(testView2.foo.length); // prints '2'    
于 2012-08-18T16:10:34.593 回答