2011-12-06 25 views
2

我建立了骨幹對象中級班:我應該如何在Backbone.js中構造類繼承?

舉例來說,我有一個App.RouterBackbone.Router繼承,我所有的收藏品將App.Router,而不是骨幹繼承。

我不確定最佳做法是什麼,或者甚至能否正常工作。

我不確定的一件事是如何在Backbone的核心庫lib中結束構造函數,它直接調用父類(在繼承中),而我用__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

我不會改變構造函數。你可以直接在初始化方法中完成所有這些。

所以:

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。