我遇到了Typescript和Backbone集合的问题。下面是一些基础:打字稿类型检查 - Backbone.Model实例无法进行类型检查
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派生的类时,我遵循this的方法,并且似乎可能是此问题的原因。基本上它将TS类的get/set属性委托给基础的Backbone.model.get()/ set(),后者又设置attributes
属性上的值。
看来我不得不要么放弃这一做法(希望这是问题),或者想出一个办法做类似或baseChartModel.attributes
对象和我的类原型为App.BackBone.Models.ScatterPlotModel
instanceof
一个松散耦合的类型检查
这断点是在与instanceof
比较
任何想法行了?
感谢您抽出一展身手,在此,虽然它不是相当的解决方案。我现在意识到这个问题的全部范围,所以我发布了一个单独的问题(http://stackoverflow.com/questions/15775092/typescript-with-typelite-run-time-type-checking)以获得更一般的解决方案。 – parliament