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

时间:2011-12-06 15:47:18

标签: javascript inheritance backbone.js

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

例如,我有App.Router继承自Backbone.Router,我的所有馆藏都将继承App.Router而不是Backbone。

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

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

我还扩展了一个基础对象来启用泛型方法。

这看起来好吗?

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) {
    },

});

1 个答案:

答案 0 :(得分:1)

我不会改变构造函数。您可以直接在initialize方法中完成所有这些操作。

所以:

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

这将是更清洁的IMO。

相关问题