Skip to content

Instantly share code, notes, and snippets.

@stutrek
Last active August 29, 2015 14:07
Show Gist options
  • Save stutrek/abe639324fc9940eaaa2 to your computer and use it in GitHub Desktop.
Save stutrek/abe639324fc9940eaaa2 to your computer and use it in GitHub Desktop.

Ordered State Handler

Ordered state handlers keep track of state through a known procedure. You can provide callbacks for when an ordered state handler enters a state, exits a state, or when the state advances.

Basic Usage

var osh = orderedStateHandler(['1', '2', '3', '3.abc', '3.xyz','4']);

osh.state; // '1'

osh.on('advance', function ( state ) {
	// do stuff for every advance
});

osh.on('2', function () {
	// do stuff for change to state 2.
});
osh.on('1:leave', function () {
	// fired when we're not longer in state 1.
})

osh.on('3, 4', function () {
	// do stuff for changes to state 3 and 4.
});
osh.on('3.abc', function () {
	// do stuff for change to state 3.abc.
});
osh.on('*.abc', function () {
	// do stuff for change to any state with a second name of .abc.
});
osh.on('3:advance', function () {
	// do stuff for change from state 3 to 3:abc and from 3:abc to 3:xyz.
});

osh.advance(); // advances the state

Methods

  • osh.on/off/one( stateName, callback ) - standard event methods
  • osh.when( stateName, callback ) - triggered when the osh enters the state, or immediately if it is in that state.
  • osh.not( stateName, callback ) - same as when, except when the osh is not in that state.
  • osh.past( stateName, callback ) - triggered immediately if the state provided will follow the current state at any point before the end. Noop otherwise.
  • osh.before( stateName, callback ) - triggered immediately if the osh was in the state provided at any point in the past. Noop otherwise.
  • osh.isIn( stateName ) - returns true if the osh is in the provided state. This takes namespaces into account, so it will return true for '3' if the osh is in state '3.abc'.

Values

  • osh.state - the provided string representation for the current state.

State Names

State names are provided as an array to the factory method. They can be namespaced with a dot and do not need to be unique.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment