【发布时间】:2015-07-06 10:58:50
【问题描述】:
我正在尝试整理我的 Backbone 项目中的代码。我面临的问题之一是我在渲染的初始化函数中初始化了所有视图。我现在决定一次只初始化一个视图(及其子视图)。
页面的渲染工作正常,我可以在视图之间前后交换。硬刷新页面(F5 等)后,视图中绑定的事件会触发,但是一旦我移动到另一个视图,这些事件就不再触发。我不明白为什么在第二次初始化时应该完全删除先前的视图。然后我们应该得到一个干净的渲染,就像刷新后第一次加载一样。谁能解释为什么事件没有触发?
以下是演示问题的代码示例:
newView: function(view){
//Check if the holding variable is defined. If it is then
//call the close function
if (routerView == undefined){
console.log("routerview is undefined")
} else {
// This calls a function on the view which will remove any
//children, once it's done that it will remove its self.
routerView.close();
}
// When removing the view it removes the parent element in the index file.
// Here we add the container back in and set it to the new view's el
if ( $('#AppContainer').length == 0 ){
// Add new div container to the app and assign it to the 'el'
view.el = $('body').prepend('<div id="AppContainer"></div>');
}
// Return view to the route for rendering.
return routerView;
},
其中一个视图中的关闭函数如下所示:
close: function(){
//Deal with any child views here as well.
this.remove();
},
最后,在我们调用 newView 函数的路径中会是这样的
admin: function(){
// Call the newView function with a new instance of the AdminView and then assign it back
this.adminView = router.newView( new AdminView({ el : $("#AppContainer")} ));
//Render the view
this.adminView.render();
},
【问题讨论】:
-
routerView是全球性的吗?您如何在 AdminView 中注册事件,您在其中调用newView? -
感谢@akoskm 的快速回复。 routerView 在需要使用的
define中定义。我在视图中使用events对象来监听点击事件等。
标签: javascript memory backbone.js model-view-controller view