stateful.js

0.1.0 • Public • Published

Stateful.js

Stateful is an implementation of the State pattern in JavaScript. Read the linked article to understand why you would apply this instead of using any FSM implementation out there.

Example

This is a trivial example, but illustrates how you would use Stateful:

function TrafficLight() {
    this.state = new Stateful(this, "stop", TrafficLight.States);
}
TrafficLight.States = {};

TrafficLight.States.stop = {
    color: "red",
    next: function() {
        this.state.transition("go");
    },
    monitorInfractions: function() {
        // Turn on the camera and make sure nobody breaks the rules.
    }
}

TrafficLight.States.go = {
    color: "green",
    next: function() {
        this.state.transition("caution");
    }
}

TrafficLight.States.caution = {
    color: "yellow",
    next: function() {
        this.state.transition("stop");
    }
}

var light = new TrafficLight();
light.color //=> "red"
typeof light.monitorInfractions //=> "function"
light.next()
light.color //=> "green"
typeof light.monitorInfractions //=> "undefined"
light.next()
light.color //=> "yellow"
typeof light.monitorInfractions //=> "undefined"
light.next()
light.color //=> "red"

Credits

Inspired by the ruby gem state_pattern by Daniel Cadenas. Built with the support of Cubox by Nicolás Sanguinetti.

Released under an MIT license. Check the attached LICENSE file for details.

Readme

Keywords

none

Package Sidebar

Install

npm i stateful.js

Weekly Downloads

1

Version

0.1.0

License

none

Last publish

Collaborators

  • foca