This question is quite difficult to describe in words, so let me know if it needs clarifying.
I’m very new to backbone.js, so it might be a silly question.
I want to use backbone to easily create graphs (highcharts library). I want to keep a massive json object with all common highcharts settings in my ‘defaults’ object in model. Then, I want to override some of the variables, for instance the one containing name of dom element the chart needs to be rendered in.
Here’s my code:
var app = {
Views:{},
Models:{},
Collections:{},
init:function(){
new app.Views.PageView();
}
};
$().ready(_.bind(app.init,app));
app.Models.chart = Backbone.Model.extend({
defaults:{
chart:{
renderTo:'charts',
backgroundColor:'#e1e1e1',
height:200,
width:200,
defaultSeriesType:'spline',
spacingRight:40,
animation:false
},
colors:['#000', '#AA4643'],
title:{
text:''
},
//lots lots lots of other attributes defined here.
app.Views.ChartView = Backbone.View.extend({
render : function() {
var chartContainer = this.model.attributes.chart.renderTo;
$('#charts').append("<div id="+chartContainer+"></div>");
new Highcharts.Chart(this.model.toJSON());
return this;
}
});
var chartDetails = [{chart:{renderTo:'div1'}},{chart:{renderTo:'div2'}}];
app.Views.PageView = Backbone.View.extend({
el: $("#charts"),
initialize : function(){
this.chartCollection = new app.Collections.Charts(chartDetails);
this.render();
},
render: function(){
var that = this;
_.each(this.chartCollection.models, function(item){
that.renderChart(item);
})
},
renderChart : function (item) {
var chartView = new app.Views.ChartView({
model: item
});
chartView.render();
}
});
So, the real question here is: when I define a new collection, I provide ‘chartDetails’ object, which overrides my ‘default’ specified in model. So, rather than update the defaults.charts.renderTo property, it replaces the full defaults.charts object. How do I make it keep everything what’s stored there (backgroundColor, etc), apart from the value I want to replace?
Thanks in advance
k
A very simple approach, if you had a flat representation of your model, would be something along these lines as you can define
defaultsas a functionI prefer this implementation above an implementation like this because you’re not tying your bootstrap together in one go, this might actually trigger unwanted events:
but since you have a deeply nested instead of a flat representation of your model, you will have to do some additional magic to only replace individual key/value pairs inside the nested object, as you would overwrite the whole object if you decide to extend it as in above example.
Thankfully jQuery’s
extendmethod, as opposed to underscore.js’sextendmethod provides us with adeepparameter so that you can do this: