我遇到了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