$ npm i backbone-machina
;const someFsm = ...;someFsm;someFsm;
BackboneFsm is the default and only export of this package. It extends both
Backbone.Events. In addition, it emits
exit:stateName events so you can hook into the behaviour of your FSM in the same way as you would do with
Backbone.Model et al. This fully describes the API.
New in version 1.1.0:
BackboneFsm is truly 100% compatible with both interfaces it extends. You can use
'all' interchangeably as wildcards when subscribing to events.
eventListeners option is supported as well. As a result,
BackboneFsm can now be used in hierarchical settings as a drop-in replacement for
Why you should use this
If you are using Backbone, then you already have some powerful tools at your disposal for managing (changes of) state:
Collectionfor the state of your data;
Viewfor the state of your document;
Routerfor the state of the URL that is shown in the browser.
There is fourth type of state, however, that none of these classes captures very well. I would call this contextual state. Examples of contextual state include
- whether the user has authenticated or not;
- whether a search is blank, being edited, submitted, successful or unsuccessful;
- whether there is still a connection with the backend.
Finite state machines are ideal for managing contextual state. There are many libraries out there that provide finite state machines, but I believe machina is the most declarative and also the most powerful of them all. To my knowledge, backbone-machina is the first library that marries Backbone and machina. Head to http://machina-js.org for some impressive examples of what a
machina.Fsm can do!
Head over to the wiki for some philosophy on Backbone project organization, which also discusses the place of
BackboneFsm in your project.