forked from jakesgordon/javascript-state-machine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo.js
More file actions
84 lines (68 loc) · 2.44 KB
/
demo.js
File metadata and controls
84 lines (68 loc) · 2.44 KB
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
Demo = function() {
var output = document.getElementById('output'),
demo = document.getElementById('demo'),
panic = document.getElementById('panic'),
warn = document.getElementById('warn'),
calm = document.getElementById('calm'),
clear = document.getElementById('clear'),
count = 0;
var log = function(msg, separate) {
count = count + (separate ? 1 : 0);
output.value = count + ": " + msg + "\n" + (separate ? "\n" : "") + output.value;
refreshUI();
};
var refreshUI = function() {
setTimeout(function() {
demo.className = fsm.state;
panic.disabled = fsm.cannot('panic', true);
warn.disabled = fsm.cannot('warn', true);
calm.disabled = fsm.cannot('calm', true);
clear.disabled = fsm.cannot('clear', true);
}, 0); // defer until end of current tick to allow fsm to complete transaction
};
var fsm = new StateMachine({
transitions: [
{ name: 'start', from: 'none', to: 'green' },
{ name: 'warn', from: 'green', to: 'yellow' },
{ name: 'panic', from: 'green', to: 'red' },
{ name: 'panic', from: 'yellow', to: 'red' },
{ name: 'calm', from: 'red', to: 'yellow' },
{ name: 'clear', from: 'red', to: 'green' },
{ name: 'clear', from: 'yellow', to: 'green' },
],
methods: {
onBeforeTransition: function(lifecycle) {
log("BEFORE: " + lifecycle.transition, true);
},
onLeaveState: function(lifecycle) {
log("LEAVE: " + lifecycle.from);
},
onEnterState: function(lifecycle) {
log("ENTER: " + lifecycle.to);
},
onAfterTransition: function(lifecycle) {
log("AFTER: " + lifecycle.transition);
},
onTransition: function(lifecycle) {
log("DURING: " + lifecycle.transition + " (from " + lifecycle.from + " to " + lifecycle.to + ")");
},
onLeaveRed: function(lifecycle) {
return new Promise(function(resolve, reject) {
var msg = lifecycle.transition + ' to ' + lifecycle.to;
log("PENDING " + msg + " in ...3");
setTimeout(function() {
log("PENDING " + msg + " in ...2");
setTimeout(function() {
log("PENDING " + msg + " in ...1");
setTimeout(function() {
resolve();
}, 1000);
}, 1000);
}, 1000);
});
}
}
});
fsm.start();
return fsm;
}();