backbone.js构造函数可以返回一个子类吗?

时间:2014-10-23 18:16:13

标签: javascript inheritance backbone.js

我们有一个Backbone View超类,它有六个子类扩展它。每个子类用于呈现特定的模型类型。超类本身并不是真正实例化的有用的东西。但是能够使用Model调用该超类构造函数并使其返回所提供模型的正确子类的View非常方便。可以用Backbone完成这样的事情吗?

1 个答案:

答案 0 :(得分:0)

好吧,我通过定义一个'构造函数'来实现它,它通过检查'templateName'来确定它是直接调用还是通过继承调用,这是我所有子类定义的属性。如果直接调用它,它会创建一个所需类型的新对象并返回它;否则它会延伸到它的父构造函数。

我今天学到的东西:它是一个方便的JS功能,如果构造函数返回一个对象,该对象将替换'this'并成为新对象。

Canonical doc on the JS new() function

我的构造函数如下所示:

constructor: function(options){

 // without a model we can't know what class to be.
 if (_.isUndefined(options) || _.isUndefined(options.model) || ! options.model.has('type'))
  throw new Error('new ThingView() called without a valid model.');

 // Because we're replacing ourselves with a subclass, constructor will execute twice.
 if (! this.templateName) { 
  // first time through: replace ourselves with a child
  var viewName = 'AssetAttributeView_' + options.model.get('type');
  return new Views[viewName](options); // replace ourselves with one of these

 } else { 
  // second time through: apply our parent's constructor.
  Backbone.View.apply(this, arguments);
 }
}