尝试使用Chrome中的堆快照工具来管理Backbone的内存管理。视图上有一个后退按钮,当点击该按钮时,将通过骨干路由器用新的视图切换当前视图。
我在初始页面上拍摄快照,使用后退按钮导航到页面,单击后退按钮并拍摄另一张快照。我希望使用比较选项将堆快照相同。然而,旧的模型/集合似乎没有被清除(它们在快照中以白色突出显示,即仍然可以通过图的根访问)。此外,它们看起来也不会被删除(快照中的相同白色突出显示)。
我已将图表链接起来以帮助解释(http://i.stack.imgur.com/mlN2I.jpg)。假设视图V1嵌套三个视图,其中V2包含模型M1,V3保持模型M2,V4保持骨干集合C1。 M1监听对M2的更改并相应地更新自身。为了正确删除视图V1,完成以下操作:
这足以完全清除视图吗?似乎大多数在线资源都讨论了对骨干视图的正确处理,而不是其模型/集合。
非常感谢任何帮助。感谢。
答案 0 :(得分:2)
使用此方法清除内存中的子视图和当前视图。
//FIRST EXTEND THE BACKBONE VIEW....
//Extending the backbone view...
Backbone.View.prototype.destroy_view = function()
{
//for doing something before closing.....
if (this.beforeClose) {
this.beforeClose();
}
//For destroying the related child views...
if (this.destroyChild)
{
this.destroyChild();
}
this.undelegateEvents();
$(this.el).removeData().unbind();
//Remove view from DOM
this.remove();
Backbone.View.prototype.remove.call(this);
}
//Function for destroying the child views...
Backbone.View.prototype.destroyChild = function(){
console.info("Closing the child views...");
//Remember to push the child views of a parent view using this.childViews
if(this.childViews){
var len = this.childViews.length;
for(var i=0; i<len; i++){
this.childViews[i].destroy_view();
}
}//End of if statement
} //End of destroyChild function
//Now extending the Router ..
var Test_Routers = Backbone.Router.extend({
//Always call this function before calling a route call function...
closePreviousViews: function() {
console.log("Closing the pervious in memory views...");
if (this.currentView)
this.currentView.destroy_view();
},
routes:{
"test" : "testRoute"
},
testRoute: function(){
//Always call this method before calling the route..
this.closePreviousViews();
.....
}
//Now calling the views...
$(document).ready(function(e) {
var Router = new Test_Routers();
Backbone.history.start({root: "/"});
});
//Now showing how to push child views in parent views and setting of current views...
var Test_View = Backbone.View.extend({
initialize:function(){
//Now setting the current view..
Router.currentView = this;
//If your views contains child views then first initialize...
this.childViews = [];
//Now push any child views you create in this parent view.
//It will automatically get deleted
//this.childViews.push(childView);
}
});
答案 1 :(得分:0)