Note that there are some explanatory texts on larger screens.

plurals
  1. POBackbone.js state management / view initialization based on url fragment
    text
    copied!<p>I'm trying to keep track of the state in this app using Backbone.js:</p> <p><img src="https://i.stack.imgur.com/MW1zi.png" alt="enter image description here"></p> <p>I have a "ChartAppModel" with a set of defaults:</p> <pre><code>ChartAppModel = Backbone.Model.extend({ defaults: { countries : [], selectedCountries : [], year : 1970, }, initialize: function() { loadAbunchOfData(); checkStartState(); } }); </code></pre> <p>If given a start fragment, this default state should however be overwritten:</p> <pre><code>var startState = $.deparam.fragment(); //using Ben Alman's BBQ plugin this.set({selectedCountries: startState.s, year: startState.y}); </code></pre> <p>Now, for example the SidebarView is ready to be updated:</p> <pre><code>ChartAppViewSidebar = Backbone.View.extend({ initialize: function(){ this.model.bind("change:selectedCountries", this.render); }, render : function(){ [... render new sidebar with check boxes ...] }, </code></pre> <p>Problem is I also have an event handler on the sidebar that updates the model:</p> <pre><code>events: { "change input[name=country]": "menuChangeHandler", }, menuChangeHandler : function(){ [... set selectedCountries on model ...] }, </code></pre> <p>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:</p> <pre><code>ChartAppModel = Backbone.Model.extend({ initialize: function() { this.bind("change", this.setState); } }); </code></pre> <p>... and relatively soon this state-manager will collapse ...</p> <p><strong>Questions:</strong></p> <p>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)</p> <p>2) How can I avoid my views setting an attribute on the model which they themselves listen for? </p> <p>3) How can I push a new state based on a part of the model?</p> <p>Bonus :)</p> <p><em>4) How would you lay out the code for the app described?</em></p> <p>Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload