2011-12-06 18 views
2

私はバックボーン・オブジェクトの中間クラス構築しています:例えばBackbone.jsでクラスの継承をどのように構造化する必要がありますか?

を、私はBackbone.Routerから継承App.Routerを持っている、すべての私のコレクションはApp.Routerの代わりに、バックボーンから継承します。

ベストプラクティスが何であるか、またはそれが正しく機能するかどうかはわかりません。

バックボーンのコアライブラリで、コンストラクタをどのように終了するのかが分かりません。親のプロトタイプを__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) { 
    }, 

}); 
+0

可能な複製:http://stackoverflow.com/questions/6968487/sub-class-a-backbone-view-sub-class-retain-events – PhD

答えて

1

私はコンストラクタを変更しません。これをすべてinitializeメソッドで直接行うことができます。

ので:

非常にクリーンIMOになります
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); 

関連する問題