Reputation: 456
I'm writing a backbone application that does OLS Regression and draws the data from two different JSONs in two separate collections.
var Ads_Per_Day = Backbone.Collection.extend({
model: DataModel,
url: 'assets/ads_per_day.json'
});
var ads_per_day = new Ads_Per_Day()
ads_per_day.fetch({
reset:true
});
var Age_Per_Day = Backbone.Collection.extend({
model: DataModel,
url: 'assets/age_all.json'
});
var age_per_day = new Age_Per_Day()
ads_per_day.fetch({
reset:true
});
I've tried to include the two collections that hold the JSONs in a single view, using this method:
var dataView = new DataView({
collection: {
ads: ads_per_day,
age: age_per_day
},
model: choiceModel,
el: '#content'
});
I initialize both parts of the collection like so:
var DataView = Backbone.View.extend({
initialize: function(){
this.ads = this.collection.ads;
this.age = this.collection.age;
this.listenTo(this.ads, 'reset', this.render);
this.listenTo(this.model, 'change', this.update);
this.parser = d3.time.format('%Y-%m-%d').parse;
},
It would appear one can reference either collection using their assigned names, but when I call map on the collections separately data is only returned from the first JSON. Not that only 'x' and 'y' contain data, but that 'a' and 'b' draw from the wrong JSON, they include data, but not from the JSON in the this.age collection.
getData: function(){
var parse = this.parser;
var xVar = this.model.get('x');
var yVar = this.model.get('y');
var aVar = this.model.get('a');
var bVar = this.model.get('b');
return this.ads.map(function(model){
return {
x: parse(model.get(xVar)),
y: model.get(yVar),
};
})
return this.age.map(function(model){
return {
a: parse(model.get(aVar)),
b: model.get(bVar)
};
})
}
How can I reference the correct collection, when they're both contained in a single view?
Upvotes: 1
Views: 585
Reputation: 7557
As you know, the problem was that you were returning twice from .getData()
. You were asking how to best remedy this, and here is an alternative to splitting .getData()
into two, by instead returning both maps in an array. You can also use the .toJSON()
method of backbone to get rid of most of the variables. Finally, underscore's map lets you specify your context, so you don't have to rename this.parser
:
getData: function(){
var attrs = this.model.toJSON();
var adsMap = this.ads.map(function(model) {
return {
x: this.parser(model.get(attrs.x)),
y: model.get(attrs.y),
};
}, this);
var ageMap = this.age.map(function(model){
return {
a: this.parser(model.get(attrs.a)),
b: model.get(attrs.b)
};
}, this);
return [adsMap, ageMap];
}
Which solution is better depends on your needs of course :).
Upvotes: 1