我需要用一些自己的成员来扩展主要的 Backbone 功能( View 、模型、路由器)。但是,以下内容无法正常工作:
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,因为引用是相同的。
任何人都知道如何扩展这些对象吗?
提前致谢:)
狮子座
最佳答案
通常您不会扩展标准 View ,而是创建您自己的基本 View 类型。您应该避免更改 Backbone 原型(prototype)上的值。
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'
关于javascript - 扩展 Backbone 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12020045/