myView = Backbone.View.extend({
//event binding etc etc
render: function() {
//render some DOM
}
})
anotherView = Backbone.View.extend({
events: {
'click .selector doThis'
},
createNewView: function() {
var view = new myView();
}
})
createNewView
may be called multiple times. My understanding is that the variable view
will not necessarily be removed by JavaScript's built-in garbage collection because it references objects/code which still exists when the createNewView
function completes.
Is this correct? How to deal with this?
My current approach is to initialise myView
once at the level of my app:
myApp.view = new myView()
Then in createNewView
I just call render on this:
myApp.view.render()
Essentially, I only ever have one of them and I re-use it.
An alternative approach is to track the creation of sub views in an array and then I call .remove()
on each one in turn when I know they are no longer needed.
Am I on the right track?
It occurs to me that the second approach is better because if myView
created bound callbacks on other objects with listenTo
, these would not be removed simply by re-assigning the variable. That is, if I am calling new
to instantiate a new instance of the view, I should call remove()
on the being discarded instance first... It seems.