javascript - Backbone JS : How to clean up views when navigate to another url?

标签 javascript backbone.js

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

此应用程序没有模型/集合,只有 View 。

谢谢!

部分代码:

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")
      });
    }
 });

最佳答案

如果你愿意,你可以只使用主干的事件机制来做到这一点。

您只需要创建一个全局事件路由器,然后让您的每个 View 都监听一个 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.
    }
});

那么这只是在您的路由器/其他地方调用 dispatcher.trigger( 'OnClose' ) 来触发关闭函数的情况。

作为一种捷径,假设您想在每次导航时执行此关闭操作,您可以只在路由器上注册事件(可以是此处的自定义“OnClose”事件,也可以是“all”事件以获取每次导航)尽管您必须小心确保事件按照您期望的顺序调用。

也可能将部分代码重构为 Backbone.View.prototype 或类似代码,但我会把它留给其他人去做。

关于javascript - Backbone JS : How to clean up views when navigate to another url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9960353/

相关文章:

javascript - 如何将此 Python 代码转换为 Node.js

javascript - 如何在 React.js 中检测页面滚动到顶部?

javascript - Backbone - 复选框保持选中状态?

javascript - Handlebars 模板未定义

javascript - Typescript debounce函数不调用作为参数传递的函数

javascript - 查找页面上的每个 radio 组

javascript - 有没有办法在插入html时触发事件?

backbone.js - Backbone.js 是否适用于 IE6?在尝试使用 Backbone.js 支持 IE6 时需要小心处理哪些类型的事情?

javascript - Backbone 基础知识

javascript - 将 rowindex 从 gridview 项目点击传递给 javascript 函数