Skip to content

machina.fsm.constructor

Jim Cowart edited this page Feb 2, 2015 · 2 revisions

Calling new machina.Fsm( options )

When you are creating a new FSM, the constructor function takes one argument: an options object providing the FSM instance its states, handlers and other properties/behavior which it needs to function.

Fsm instances will contain any properties returned from machina.utils.getDefaultOptions and getDefaultClientMeta.

The values on the options argument can include/override any of the members provided by getDefaultOptions and getDefaultClientMeta - along with any other property or methods you provide. The most common instance members you will utilize are as follows:

Member Description
initialState A string value indicating the initial state in which the FSM should exist. Defaults to uninitialized.
eventListeners An object which holds event subscribers for events emitted from the FSM. It is an object that has a key for any event emitted, and the value of the key is an array of subscriber callbacks. Normally, subscribers get added by calling fsmInstance.on("eventName", callback), but providing this argument allows you to set multiple subscribers up in advance as part of creating the FSM.
states An object where each top-level (own) property is a 'state', and each state property is an object containing the input handlers the FSM should utilize while in that state. Input handlers can be functions, a string value that matches another state name, or one of the special handlers (_onEnter, _onExit or the * catch-All handler). Please note that not including a states object will render your FSM useless (unless it's being used a base for more constructor extensions).
namespace A string value used as a namespace for the FSM, should it be (for example) wired into a message bus.
initialize A function that is executed once the instance of the FSM has been created. This gives you a chance to perform any initialization concerns on the FSM before machina itself triggers the newfsm event and before the FSM transitions into the initialState.

One of many possible examples of new-ing up an FSM:

var fsm = new machina.Fsm( {

	namespace : "connectivity",

	initialState : "offline",

	states : {
		probing : {
			_onEnter : function () {
				var self = this;
				if ( !self.wiredUp ) {
					useStethoscope( self, stethoscope );
					self.wiredUp = true;
				}
				stethoscope.checkHeartbeat();
			},
			heartbeat : "online",
			"no-heartbeat" : "disconnected",
			"go.offline" : "offline",
			"*" : function () {
				this.deferUntilTransition();
			}
		},

		online : {
			"window.offline"  : "probing",
			"appCache.error"  : "probing",
			"request.timeout" : "probing",
			"go.offline"      : "offline"
		},

		disconnected : {
			"window.online"        : "probing",
			"appCache.downloading" : "probing",
			"go.online"            : "probing",
			"go.offline"           : "offline"
		},

		offline : {
			"go.online" : "probing"
		}
	}
} );