我在使用Typescript和Backbone Collections时遇到了问题。以下是一些基础知识:
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();
});
在 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
从未评估为true之外,因为似乎从Backbone.Model
派生的'类类型'被分配给Backbone.Model.attributes
而不是该类本身的实例。我认为这是因为在实现从Backbone.Model派生的类时,我遵循了这个方法,这似乎可能是这个问题的原因。基本上,它将TS类上的get/set属性委托给底层的Backbone.model.get()/set(),后者又将值设置在attributes
属性上。看起来我要么放弃这个方法(并希望那是问题所在),要么找出一种类似于或使用
instanceof
的松散耦合类型检查,介于baseChartModel.attributes
对象和我的类原型之间App.BackBone.Models.ScatterPlotModel
此断点位于具有instanceof
比较的行
![enter image description here](https://istack.dev59.com/zaEY2.webp)