State management for JavaScript applications
State management is very important aspect when creating responsive, high quality single-page JavaScript applications. Just think about users with slow connections or high latency. What will happen if your AJAX requests will take 5 seconds, 10 seconds. Will user's action affect the state of your model in the meantime?
Let us take a classical example: TODO application. You can find a TODO application samples implemented using all possible JavaScript MVC framework. Your TODO application will store a new TODOs and updates of existing TODOs to the server. However every server/Ajax call can take time, and also can fail. So when request is inflight would be great to provide a visual feedback to the user about that, and possible disable/enable some of the UI actions. More over we would like to modularize such code and make it easy to test and modify in future.
For a solution we can take a state chart micro-framework: Stativus. This framework is originated from refactoring of the Sproutcore-based Ki framework. The only difference is that you can use it with any MVC application framework like Backbone.js, Ember.js, or any other.
Fo our sample we will use following state chart:
When application DOM is ready and all javascript files are parsed we are in Start state. Then we move to the Initalized state. In the initalized state we trigger loading of the data from the server. This is asynchronious operation and may have two outcomes: success (Model loaded) and failure (Failed to load Model). So from Initialized in case loading is successfull, we move to Editing state or to Load failed state.
In the Editing state we give a user full power to modify our model by creating new or updating existing TODOs, however we want to persist changes to server (every change, or all changes in batch after defined timeout). So from Editing we may move to Persisting state. There we initiate an AJAX asynchronious call to server, which could bring us back to Editing state if successfull, and if not we are moving into the Persist failed state.
That's how it will looks like in the code:
As you can we declared a Start state and it has one method enterState. This method will be called when statechart is entered the state (there are other methods your statechart may have, we will talk about them later). So Start state just move our statechart to the next state, namely to Initialized.
The Initialized step is more complicated, here we load JSON data from the server, and as success callback we move to the Editing state and in case of communication failure we move to the Load failed state.
Next state is Editing:
Usually there you should react on change events from your model, but for the sake of test Editing state will just trigger a move to the Persisting state in 1 second.
Persisting state is simlar to the Loading except it pushes the model to the server. Description of the failed states I will skip for this blog. You can see the full souce code with the test in this gist. Now we can intialize the statechart by doing that:
Now if we fake some of the JQuery AJAX operations and start our statechart we will see following in the developer console:
Non-minified version of Stativus library will log the state chart transitions, it is very convinient when developing application. If you switch to the minified version, logging will no longer happen.After initial statechart is in place you could enrich it with additional actions.For example you can disable UI elements when leaving and enable them when entering the Editing state by implementing functions exitState and didEnterState like this:
Or you could show a progress window to the user when doing some long-running operations by introducing a sub-states and events, but that is a topic for another blog. Full list of supported callabck methods you could find in the Stativus documentation.
To summarize: using statechart we will not only understand and document our application structure and behavior better, we will also get a better modularization and testability of our application code. Statechart applications are simpler to develop, they are more deterministic and allow us, developers, to provider a better user exeprience without compomising the code quality and clarity.
The full source of the statechart sample from this blog you can find here.

