我有一个主页 View ,其中包含页面上的几个 subview ,当我使用路由器导航到另一个页面时,如何清理现有 View 并为我要导航到的页面构建新 View ?
此应用程序没有模型/集合,只有 View 。
谢谢!
部分代码:
Home = Backbone.View.extend({
template: "static/js/templates/home.html",
initialize: function() {
_.bindAll(this);
this.render();
},
render: function() {
var view = this;
// Fetch the template, render it to the View element and call done.
namespace.fetchTemplate(this.template, function(tmpl) {
view.el.innerHTML=tmpl();
view.subRender();
});
return this;
},
subRender: function() {
var view = this;
var videoView = new Subview1({
el: $('#wrapper1'),
homeView: view
});
var timeView = new Subview2({
el: $("#wrapper2")
});
}
});
最佳答案
如果你愿意,你可以只使用主干的事件机制来做到这一点。
您只需要创建一个全局事件路由器,然后让您的每个 View 都监听一个 CloseView
事件。然后您只需要在收到 CloseView
事件时执行所有关闭操作即可。
var dispatcher = _.clone(Backbone.Events)
Home = Backbone.View.extend({
...
initialize: function() {
...
dispatcher.on( 'CloseView', this.close, this );
}
close: function() {
// Unregister for event to stop memory leak
dispatcher.off( 'CloseView', this.close, this );
this.remove();
this.unbind();
this.views = []; // Clear the view array
}
...
});
SubView = Backbone.View.extend({
...
initialize: function() {
...
dispatcher.on( 'CloseView', this.close, this );
}
close: function() {
// Unregister for event to stop memory leak
dispatcher.off( 'CloseView', this.close, this );
// Do other close stuff here.
}
});
那么这只是在您的路由器/其他地方调用 dispatcher.trigger( 'OnClose' )
来触发关闭函数的情况。
作为一种捷径,假设您想在每次导航时执行此关闭操作,您可以只在路由器上注册事件(可以是此处的自定义“OnClose”事件,也可以是“all”事件以获取每次导航)尽管您必须小心确保事件按照您期望的顺序调用。
也可能将部分代码重构为 Backbone.View.prototype 或类似代码,但我会把它留给其他人去做。
关于javascript - Backbone JS : How to clean up views when navigate to another url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9960353/