我遇到了 Typescript 和 Backbone 集合的问题。这里有一些基础:
class BaseChartModel extends Backbone.Model { }
class ScatterPlotModel extends BaseChartModel { }
class BarChartModel extends BaseChartModel { }
class MixedChartCollection extends Backbone.Collection { public model: BaseChartModel; ... }
class ScatterPlotCollection extends Backbone.Collection { public model: ScatterPlotModel; ... }
class BarChartCollection extends Backbone.Collection { public model: BarChartModel; ... }
然后我执行以下操作:
 var scatterPlotCollection = new ScatterPlotCollection();
 var scatterPlotCollectionXhr = scatterPlotCollection.fetch({...});
 var barChartCollection = new BarChartCollection();
 var barChartCollectionXhr = barChartCollection.fetch({...});
 $.when(scatterPlotCollectionXhr, barChartCollectionXhr).done(() => {
       mixedCollection = new MixedChartCollection();
       mixedCollection.add(scatterPlotCollection.models, { silent: true });
       mixedCollection.add(barChartCollection.models, { silent: true });
       chartViewList = new MixedChartViewList({ collection: mixedCollection });
       chartViewList.render();
 });
内部渲染():
public render(){
     var self = this;
     this.$el.html(this.template({}));
     this.collection.forEach(
    (chartModel: BaseChartModel) => {
            this.$el.append(self.AddChartView(chartModel).render());                  
    }
 );
     return this;
}
public AddChartView(baseChartModel: BaseChartModel) : BaseChartView {
      var newChartView: BaseChartView;
      if(baseChartModel instanceof ScatterPlotModel){
           newChartView = new ScatterPlotView({ model: baseChartModel});
      } else if (baseChartModel instanceof BarChartModel){
           newChartView = new BarChartView({ model: baseChartModel});
      } 
      ....       
}
除了instanceof永远不会评估为真,因为似乎派生自的“类类型”Backbone.Model被分配给Backbone.Model.attributes而不是类本身的实例。我相信这是因为在实现从 Backbone.Model 派生的类时,我遵循了这种方法,似乎这可能是导致此问题的原因。基本上,它将 TS 类上的 get/set 属性委托给底层的 Backbone.model.get()/set() ,后者反过来设置attributes属性的值。
看来我必须放弃这种方法(并希望这是问题所在),或者找出一种方法来进行松散耦合的类型检查,类似于或instanceof在baseChartModel.attributes对象和我的类原型之间使用App.BackBone.Models.ScatterPlotModel
此断点位于instanceof比较
行处
有任何想法吗?