-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathstateMachine.js
148 lines (114 loc) · 3.14 KB
/
stateMachine.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/*global exports module define */
(function () {
'use strict';
(function exporter(name, definition) {
var old, lib;
// AMD
if (typeof define === 'function') {
define(definition);
// CommonJS
} else if (typeof exports === 'object') {
module.exports = definition();
// Browser
} else {
old = window[name];
lib = definition();
window[name] = lib;
window[name].noConflict = function () {
window[name] = old;
return lib;
};
}
}('stateMachine', function () {
function is(obj, name) {
return Object.prototype.toString.call(obj) === '[object ' + name + ']';
}
function extend(base) {
var i, ii
, source
, name
;
for (i = 1, ii = arguments.length; i < ii; i++) {
if (!(source = arguments[i])) { continue; }
for (name in source) {
if (!source.hasOwnProperty(name)) { continue; }
base[name] = source[name];
}
}
return base;
}
function state(name, opts) {
return extend({
name: name
, events: {}
}, opts);
}
function stateDsl(states) {
var dsl;
function buildEventShortcut(name) {
states[name] = states[name] || function () {
states.trigger(name);
};
}
return dsl = {
state: function (name, opts) {
states._states[name] = state(name, opts);
return dsl;
}
, event: function (name, from, to) {
var i, ii, fromState
;
!is(from, 'Array') && (from = [from]);
buildEventShortcut(name);
for (i = 0, ii = from.length; i < ii; i++) {
fromState = states._states[from[i]];
fromState.events[name] = to;
}
return dsl;
}
};
}
function machine(initialBuild) {
var currentState
, me = {}
, dsl = stateDsl(me)
;
extend(me, {
currentState: function (fullState) {
var curr = currentState || (function () {
var i;
for (i in me._states) {
if (me._states[i].initial) {
return me._states[i];
}
}
}());
if (fullState) {
return curr;
}
return curr && curr.name;
}
, setState: function (name) {
var prev = me.currentState(true);
currentState = me._states[name];
me.onChange(me.currentState(), prev.name);
is(currentState.enter, 'Function') && currentState.enter();
is(prev.leave, 'Function') && prev.leave();
}
, trigger: function (eventName) {
var nextState = me.currentState(true).events[eventName];
nextState && me.setState(nextState);
}
, _states: {}
, onChange: function (current, previous) { }
, build: function (builder) {
is(builder, 'Function') && builder.call(dsl, dsl);
return dsl;
}
});
is(initialBuild, 'Function') && me.build(initialBuild);
return me;
}
return machine;
}));
}());