Reputation: 3093
I have read many posts about the issue of multiple instances of the same backbone view being instantiated every time and the view hangs around in the DOM even after it's not used any more, and how to fix this by using this.remove()
and this.unbind()
But how to remove the variables declared inside the view, like so:
var myview = Backbone.View.extend({
el : '#somediv',
var1 : '',
var2 : '',
array1 : [],
initialize : function() { //init code here
},
render : function() { //rendering code here
}
});
So my question is, how do i remove instances of those variables declared there: var1, var2, array1. I have to call this view every time i click on a button. And every time i see the previous values of these variables still there. this.remove()
and this.unbind()
might just remove the view from DOM and undelegate its events bindings.
Upvotes: 1
Views: 334
Reputation: 434635
The properties you define inside the Backbone.View.extend
call are attached to the prototype and thus are shared by all instances of your view (i.e. they're sort of like class properties rather than instance properties). This should be fine with your var1
and var2
as you'd just be assigning new values per-instance; the array1
array and similar properties can be problematic though; suppose you do this:
var v = new myview;
v.array1.push('pancakes');
Creating a new instance won't deep-copy everything out of the prototype so v.array1
will refer to the array in the prototype. That means that the next new myview
will already have 'pancakes'
.
The usual solution is to initialize instance properties in the constructor. For Backbone, the constructor is initialize
:
var myview = Backbone.View.extend({
el: '#somediv',
initialize: function() {
this.var1 = '';
this.var2 = '';
this.array1 = [ ];
},
//...
});
You can also run into problems with your el: '#somediv'
as that uniquely identifies a single DOM element. As long as you're removing and recreating that element then you should be okay; I'd recommend letting the view create and destroy its own el
though, you run into fewer zombies and leaks that way.
Upvotes: 4