问题描述:

Consider the following:

 SomeView = Backbone.View.extend({

render0: function () {

var view0 = new View0();

view0.setElement("#right-block");

view0.render();

},

render1: function(event) {

var view1 = new View1();

view1.setElement("#right-block");

view1.render();

},

});

If I call render0() and then render1, what will happen to the object view0? Do I have to explicitly destroy the old view?

网友答案:

Your view0 will stay in memory as long as the DOM element #right-block exists. Because the event handlers on the DOM element is pointing to methods of your view, so it won't be garbage collected.

Ideally you should invoke view0.remove(), which will remove the element from DOM and also calls stopListening().

But in your sample code, if you do that, the element #right-block will be removed from DOM, and view1.setElement("#right-block"); won't work as expected.

In this case try invoking view0.undelegateEvents(); view0.stopListening();, and if nothing else is referring to the view instance, it'll be garbage collected

网友答案:

No, you don't have to destroy the old view. Variables in objects that themselves go out of scope do not have to be manually cleared. When they go out of scope or when the parent object is deleted, the data contained within will also be eligible for garbage collection.

相关阅读:
Top