如何交换视图模板并删除旧视图

时间:2017-06-15 22:19:05

标签: javascript backbone.js backbone-views

我有以下代码:

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}。它看起来没什么变化!

我有两个问题。

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

1 个答案:

答案 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;
},

关于仍在内存中的视图

所以它仍然存在于内存中,直到你释放任何引用。将视图对象记录到控制台会使其保持活动状态,因为它是对它的引用。

为多个视图共享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上写了详细的答案。