I'm trying to keep track of the state in this app using Backbone.js:
I have a "ChartAppModel" with a set of defaults:
ChartAppModel = Backbone.Model.extend({
defaults: {
countries : [],
selectedCountries : [],
year : 1970,
},
initialize: function() {
loadAbunchOfData();
checkStartState();
}
});
If given a start fragment, this default state should however be overwritten:
var startState = $.deparam.fragment(); //using Ben Alman's BBQ plugin
this.set({selectedCountries: startState.s, year: startState.y});
Now, for example the SidebarView is ready to be updated:
ChartAppViewSidebar = Backbone.View.extend({
initialize: function(){
this.model.bind("change:selectedCountries", this.render);
},
render : function(){
[... render new sidebar with check boxes ...]
},
Problem is I also have an event handler on the sidebar that updates the model:
events: {
"change input[name=country]": "menuChangeHandler",
},
menuChangeHandler : function(){
[... set selectedCountries on model ...]
},
So there will be a feedback loop ... And then, I'd also like a way of pushing a new state - so I listen to model changes:
ChartAppModel = Backbone.Model.extend({
initialize: function() {
this.bind("change", this.setState);
}
});
... and relatively soon this state-manager will collapse ...
Questions:
1) How do I init my views (for example "which checkboxes should be checked") based on the fragment? (any hints on best practices for state / start state that is not a typical "route" are appreciated)
2) How can I avoid my views setting an attribute on the model which they themselves listen for?
3) How can I push a new state based on a part of the model?
Bonus :)
4) How would you lay out the code for the app described?
Thanks!