我想将 BackboneJS 用于单页网站。我正在考虑使用的结构是有一个 div#pageWrapper
用于将 View 加载到
# a simple example view
class View1 extends Backbone.View
render: ->
@$el.html @template()
class AppRouter extends Backbone.Router
routes:
"": "home"
"view1": "view1"
"view2": "view2"
home: ->
# init, render, attach to body. repeat for other controller actions
view = new HomeView()
view.render()
$("#pageWrapper").html view.el
这是通常的做法吗?或者是否已经有某种设计模式可用?我还没有处理过清理工作,我需要它吗?或者这是简单地替换页面包装器的 html 的副作用?
最佳答案
是的,您确实需要正确处理 View 的关闭和删除。如果你不这样做,你最终会出现内存泄漏和“僵尸” View ——这些 View 应该死掉,但实际上却没有。
我已经写过很多关于它的文章:
http://lostechies.com/derickbailey/2011/12/12/composite-js-apps-regions-and-region-managers/
其要点是,您应该直接在 View 中管理 View 的清理,然后使用标准化流程调用 View 的清理方法。
例如,我使用一个对象在屏幕上显示/删除/替换我的 View :
Region = (function (Backbone, $) {
var currentView;
var el = "#mainregion";
var region = {};
var closeView = function (view) {
if (view && view.close) {
view.close();
}
};
var openView = function (view) {
view.render();
$(el).html(view.el);
if (view.onShow) {
view.onShow();
}
};
region.show = function (view) {
closeView(currentView);
currentView = view;
openView(currentView);
};
return region;
})(Backbone, jQuery);
只需确保您的 View 中有一个 close
方法,此代码将为您清理它。一个简单的 close
实现如下所示:
Backbone.View.prototype.close = function(){
this.remove();
this.unbind();
if (this.onClose){
this.onClose();
}
}
现在你的所有 View 都有这个 close 方法。
请参阅文章以获取更多信息。
关于jquery - BackboneJS 单页站点 : Attaching and Cleaning Up Views,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11016996/