Reputation: 850
var TestView = Backbone.View.extend({
options: {
"theList": []
},
initialize: function() {
console.log(this.options.theList.length);
this.options.theList.push("xxx");
}
});
// other place:
var view1 = new TestView();
// the console result will be 0
var view2 = new TestView();
// the console result will be 1 !!!
var view3 = new TestView();
// the console result will be 2 !!!!!!
...
Why? I think it will just console 0 every time that I new
the TestView
!
Upvotes: 1
Views: 113
Reputation: 434635
Everything inside the extend
call will be attached to the view's prototype. That means that your options
will be shared by all instances of TestView
so each time you:
this.options.theList.push("xxx");
you're pushing a string onto the exact same array that all instances are sharing/referencing through the prototype.
If you want separate options
for each instance, set it up in the view's constructor:
var TestView = Backbone.View.extend({
initialize: function() {
this.options.theList = [ ];
console.log(this.options.theList.length);
this.options.theList.push("xxx");
}
});
Upvotes: 2