2017-06-15 40 views
0

我有以下代码:如何换一个视图的模板,并删除旧的观点

switch (type) { 
    case "countdown": 
     this.render(_this.templates.countdown); 
     break; 
    case "timer": 
     this.render(_this.templates.timer); 
     if (App.Views.timer) App.Views.timer.remove(); 
     App.Views.timer = new Timer(); 
     break; 
} 

所以,我想,当模板被渲染我们除去以前的观点,因为在新的DOM链接元素改变了。但我不确定哪个旧视图真的被删除了。

因为如果我加console.log(App.Views.timer)if (App.Views.timer) App.Views.timer.remove();我得到:child {cid: "view3", $el: jQuery.fn.init(1), el: div#timer.timer}。它看起来没有任何改变!

我有两个问题。

  1. 从内存中删除视图是否正确?
  2. 如果我有一个可以更改模板的div,创建新的View是否正确?不幸的是,只隐藏模板的解决方案不适合我的情况。

回答

2

什么是视图的remove函数呢?

View's remove function只是从DOM中删除元素,同时解除绑定任何DOM相关事件和主干特定事件。

移除从DOM的图,其el,并调用stopListening到 除去该视图有listenTo“d任何结合事件。

code for the remove function是:

// Remove this view by taking the element out of the DOM, and removing any 
// applicable Backbone.Events listeners. 
remove: function() { 
    this._removeElement(); 
    this.stopListening(); 
    return this; 
}, 

关于内存

的观点仍然所以还是住在内存中,直到您松开留下的任何引用。将视图对象记录到控制台使其保持活动状态,因为它是对它的引用。

共享一个div的多个视图

我不会去这样的路。您可以使用带有路线的Backbone Router,然后创建某种布局视图,而不是开关箱。

一个超级简单的布局图看起来是这样的:

var LayoutView = Backbone.View.extend({ 
    initialize: function() { 
     // caching the jQuery object on init 
     this.$content = this.$('#content'); 
    }, 
    setContent: function(view) { 
     var content = this.content; 
     if (content) content.remove(); 
     content = this.content = view; 
     this.$content.html(content.render().el); 
    }, 
}); 

使用路由器中:

var Router = Backbone.Router.extend({ 
    routes: { 
     'about': 'aboutRoute', 
     'contact': 'contactRoute', 
     // put the catch-all last 
     '*home': 'homeRoute', 
    }, 
    initialize: function() { 
     // create the layout once here 
     this.layout = new views.Application({ 
      el: 'body', 
     }); 
    }, 
    homeRoute: function() { 
     var view = new views.Home(); 
     this.layout.setContent(view); 
    }, 
    aboutRoute: function() { 
     var view = new views.About(); 
     this.layout.setContent(view); 
    }, 
    contactRoute: function() { 
     var view = new views.Contact(); 
     this.layout.setContent(view); 
    } 
}); 

我写了一篇关于how to use a router with a simple layout view了详细的解答。

+0

我的错误,我没有说通过选择字段来改变视图,而不是链接。但我认为第二部分对其他人有用。 –

+0

@VasiliyRusin同样的概念适用,不要改变视图的模板,使用'setContent'技巧在视图内改变视图。 –

+0

好的,谢谢我试试。 –