I have a problem with Typescript and Backbone collections. Here are some basics:
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; ... }
Then I do the following:
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(); });
Inside 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}); } .... }
Except instanceof , true is never evaluated, because it seems that the class type obtained from Backbone.Model is assigned to Backbone.Model.attributes , and is not an instance of the class itself. I believe this is due to the fact that when implementing my classes that come from Backbone.Model, I followed this up and it looks like this might be causing this problem. This basically delegates the get / set properties of the TS class to the underlying Backbone.model.get () / set (), which in turn sets the values ββin the attributes property.
It seems that I need to either abandon this approach (and hope that this was a problem), or figure out a way to conduct a loosely coupled type check similar to or using instanceof between the baseChartModel.attributes object and the prototype of my class for App.BackBone.Models.ScatterPlotModel
This breakpoint is on line with instanceof comparison 
Any ideas?
source share