Как мне структурировать наследование классов в Backbone.js? - PullRequest
2 голосов
/ 06 декабря 2011

Я создаю промежуточные классы для объектов 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 Ответ

1 голос
/ 06 декабря 2011

Я бы не стал менять конструктор. Вы можете сделать все это прямо в методе 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);

Это будет намного чище ИМО.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...