【问题标题】:Events not firing after reinitialising backbone views重新初始化主干视图后未触发事件
【发布时间】: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


【解决方案1】:

我已经做了更多的工作来调查这个问题并且我发现了它。问题有两个问题,但出现在同一行代码中。

view.el = $('body').prepend('<div id="AppContainer"></div>');   

我在主干网docs 上发现您应该使用 setElement 函数来更改视图的元素。然后这会传输所有绑定的事件,这意味着它们现在可以工作了。

然后我发现$('body').prepend('&lt;div id="AppContainer"&gt;&lt;/div&gt;') 会返回对body 的引用,而不是新的#AppContainer,但它实际上返回对body 的引用,这意味着视图的内容被放置在body 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多