You want to create a simple login page for your new website, all written to be dynamic using Backbone.js and Marionette.js. To accomplish this, you listen for the login button to be pressed and then use jQuery to disable the form controls and display a loading message. An invalid login message comes back, so you reenable the form, highlight the incorrect fields, display a message, etc. The user presses login again… uh oh, you forgot to add code that removes the highlighted fields and hides the error message div.
Your view logic is starting to become tedious and you never know if you’ve covered all the possible paths through your user interface. However, there may be a solution to make your view more organized and predictable: states.
The State Machine
The first step to implementing this is coming up with the states that you’re going to need. After starting with some obvious state and thinking about each situation, I came up with the following state machine.
This assumes that you have a backend API for authenticating users that returns HTTP 200 when the username and password are found to lead to a valid user, and HTTP 404 when the combination of username and password are not found in the users database.
Marionette.js Frontend Code
Isn’t That Better?
Instead of having to code up a bunch of messy if/else if statements to transition your UI between the states and handle reverting elements back to their defaults when needed, you just have a single switch statement that takes your default UI and modifies it appropriately for the state that your model is in. This will make your UI logic much more readable, predictable, and extensible.
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.