backbone-machina
v1.1.0
Published
machina.Fsm dressed as a fourth Backbone pillar next to Model, View and Router
Downloads
6
Maintainers
Readme
backbone-machina
machina.Fsm dressed as a fourth Backbone pillar next to Model, View and Router.
Quickstart
$ npm i backbone-machina
import BackboneFsm from 'backbone-machina';
const someFsm = new BackboneFsm({...});
someFsm.on('enter:someState', (fsm, action) => {...});
someFsm.on('exit:anotherState', (fsm, action) => {...});
BackboneFsm
is the default and only export of this package. It extends both machina.Fsm
and Backbone.Events
. In addition, it emits enter:stateName
and 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 '*'
and 'all'
interchangeably as wildcards when subscribing to events. machina.Fsm
’s eventListeners
option is supported as well. As a result, BackboneFsm
can now be used in hierarchical settings as a drop-in replacement for machina.Fsm
.
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:
Model
andCollection
for the state of your data;View
for the state of your document;Router
for 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!
Recommended usage
Head over to the wiki for some philosophy on Backbone project organization, which also discusses the place of BackboneFsm
in your project.