javascript - 我应该如何在 Backbone.js 中构造类继承?

标签 javascript inheritance backbone.js

我正在为 Backbone 对象构建中间类:

例如,我有一个 App.Router 继承自 Backbone.Router,我的所有集合都将从 App.Router 继承 Backbone 。

我不确定最佳实践是什么/或者它是否能正常工作。

我不太确定的一件事是如何结束构造函数,在 Backbone 的核心库中,它确实直接调用父级(在继承中),而我用 __super__ 调用父级原型(prototype)。

我还扩展了一个基本对象以启用通用方法。

这看起来可以吗?

App.Router = Backbone.Router.extend({

    // Reference to views objects instanciated
    views: {},

    // Reference to collections objects instanciated
    collections: {},

    // Class constructor (can be overriden in subclass with the need of a parent call)
    constructor: function(options) {
        console.log(" \u2192App.Router::constructor()", [this, arguments]);
        var self = this;

        // Configure instance
        this._configure(options || {});

        // Extend App.Object
        _.extend(this, App.Object);

        // SO? : Is this the correct way to end constructor?
        return App.Router.__super__.constructor.apply(this, arguments);
    },

    // Class initialization (override in subclass without the need of a parent call)
    initialize: function(config) {
        d&&console.log(this.name + "::initialize()", [this, arguments]);
    },

    // Performs the initial configuration of a Router with a set of options.
    // Keys with special meaning are attached directly to the class
    _configure : function(options) {
      if (this.options) options = _.extend({}, this.options, options);
      var classOptions = ['registerKey', 'parent', 'collections', 'views'];
      for (var i = 0, l = classOptions.length; i < l; i++) {
        var attr = classOptions[i];
        if (options[attr]) this[attr] = options[attr];
      }
      this.options = options;
    },

    // Render a view with a collection & optional data
    render: function(className, options) {
    },

});

最佳答案

我不会更改构造函数。您可以直接在初始化方法中执行所有这些操作。

所以:

App.Router = Backbone.Router.extend({
  initialize: function(options){
    this._configure(options)
    // no need to call super initialize as it is empty
  },
  _configure: function(){...}
});
_.extend(App.Router.prototype, App.Object);

在我看来,这将更加清洁。

关于javascript - 我应该如何在 Backbone.js 中构造类继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8402690/

相关文章:

javascript - 如何将 Backbone View 事件哈希定义为函数?

javascript - 为什么启用 html5mode 后 AngularJS 路由会被破坏?

javascript - 如何将 Terser 与 webpack 结合使用

ruby-on-rails - Rails 3.2 JS-heavy 应用程序的设计模式

java - 区分父类(super class)和子类之间的变量

python - 继承自matplotlib

javascript - 将数据绑定(bind)到 DOM 的示例

javascript - 如何使用 PHP 和 Ajax 实时读取文件

Javascript - 如何检查当前时间是否在两个不同时间之间

c# - 如何从 C# 中的封闭构造类中获取基类对象