我有以下代码:
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;
}
因此,正如我想的那样,当模板被渲染时,我们将删除之前的View,因为新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}
。它看起来没什么变化!
我有两个问题。
答案 0 :(得分:2)
remove
函数有什么作用? View's remove
function只需从DOM中删除元素,同时解除任何与DOM相关的事件和Backbone特定事件的绑定。
从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; },
所以它仍然存在于内存中,直到你释放任何引用。将视图对象记录到控制台会使其保持活动状态,因为它是对它的引用。
我不会这样做。您可以使用带有路由的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);
}
});