【发布时间】:2013-05-09 20:43:39
【问题描述】:
我遇到了 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 的类时,我遵循了this 方法,似乎这可能是导致此问题的原因。基本上,它将 TS 类上的 get/set 属性委托给底层 Backbone.model.get()/set(),后者反过来设置 attributes 属性上的值。
看来我必须要么放弃这种方法(并希望这是问题所在),要么想办法在baseChartModel.attributes 对象和我的类原型之间进行类似于或使用instanceof 的松散耦合类型检查App.BackBone.Models.ScatterPlotModel
这个断点在与instanceof比较的那一行
有什么想法吗?
【问题讨论】:
标签: backbone.js typescript backbone.js-collections