Backbone JS:如何在导航到另一个URL时清理视图?

use*_*652 14 javascript backbone.js

我有一个Homeview,其中包含一些页面上的子视图,当我使用路由器导航到另一个页面时,如何清理现有视图,并为我要导航到的页面构建新视图?

此应用程序没有模型/集合,只有视图.

谢谢!

部分代码:

Home = Backbone.View.extend({
    template: "static/js/templates/home.html",

    initialize: function() {
      _.bindAll(this);
      this.render();
    },

    render: function() {
      var view = this;

      // Fetch the template, render it to the View element and call done.
      namespace.fetchTemplate(this.template, function(tmpl) {
        view.el.innerHTML=tmpl();
        view.subRender();
      });

      return this;
    },
    subRender: function() {
      var view = this;
      var videoView = new Subview1({
        el: $('#wrapper1'),
        homeView: view
      });
      var timeView = new Subview2({
        el: $("#wrapper2")
      });
    }
 });
Run Code Online (Sandbox Code Playgroud)

obm*_*arg 9

如果您愿意,您可以使用骨干事件机制来执行此操作.

您只需要创建一个全局事件路由器,然后让每个视图监听一个CloseView事件.然后,您只需要在接收CloseView事件时执行所有关闭操作.

var dispatcher = _.clone(Backbone.Events)

Home = Backbone.View.extend({
    ...
    initialize: function() {
        ...
        dispatcher.on( 'CloseView', this.close, this );
    }
    close: function() {
        // Unregister for event to stop memory leak
        dispatcher.off( 'CloseView', this.close, this );
        this.remove();
        this.unbind();
        this.views = [];   // Clear the view array
    }
    ...
});

SubView = Backbone.View.extend({
    ...
    initialize: function() {
        ...
        dispatcher.on( 'CloseView', this.close, this );
    }
    close: function() {
        // Unregister for event to stop memory leak
        dispatcher.off( 'CloseView', this.close, this );
        // Do other close stuff here.
    }
});
Run Code Online (Sandbox Code Playgroud)

然后,只是dispatcher.trigger( 'OnClose' )在您的路由器/其他地方调用以触​​发关闭功能的情况.

作为一种快捷方式,假设您想在每个导航上执行此关闭,您可以在路由器上注册事件(这里是自定义'OnClose'事件,或者只是获取每个导航的'all'事件)必须要小心,事件是按照你期望的顺序调用的.

也有可能将这些代码重构为Backbone.View.prototype或类似代码,但我会将其留给别人去做.