我正在为 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/