# Overview

backbone-fsm is a Finite State Machine library built on top of Backbone's Model primitive.

Implement a FSM by defining possible transitions, and integrate it with your backbone model.

## Dependencies

Underscore, Backbone

## Usage

As an initial example, let's implement a virtual turnstile. This turnstile allows two actions: letting a person pass, and having a coin inserted. The turnstile also stores a state, and keeps track of whether it is locked. While locked, a person cannot pass. Inserting a coin will change the turnstile state to be unlocked, allowing a person to pass. Once a person passes, the turnstile becomes locked again.

We first create a FSM factory using FSM.define() and giving it all our transitions.

require(["backbone-fsm", "backbone"], function(FSM, Backbone) {
var TurnstileFSM = FSM.define(
{
action: {person_entered: true},
guard: {locked: false},
result: {locked: true}
},
{
action: {coin_inserted: true},
result: {locked: false}
}
);

//...


Here we've called FSM.define() with two arguments, both are javascript objects with an action and result key (and an optional guard key).

The action key is a matcher for the action being done, and the guard key matches the current state. If both the action and guard match, the result is applied to the FSM.

FSM.define() just returns a factory method, in which you'll pass a backbone model:

var Turnstile = TurnstileFSM(
Backbone.Model.extend({
defaults: {
locked: true
}
})
);


Now, we have a backbone model representing a turnstile, which begins in a locked state, with two additional methods, can() and transition():

var myTurnstile = new Turnstile();
myTurnstile.get("locked"); // true
myTurnstile.can("person_entered"); // false
myTurnstile.transition("coin_inserted", true);
myTurnstile.get("locked"); // false
myTurnstile.can("person_entered"); // true


stuff