-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
82 lines (64 loc) · 1.83 KB
/
index.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
// from https://gist.github.com/foca/3462441
/**
* @param object
* @param initialState
* @param interfaces
* @param onInitialize
*/
export function Stateful(object, initialState, interfaces, onInitialize) {
let currentState;
this.interfaces = interfaces = interfaces || object.constructor.States;
if (typeof interfaces == 'undefined') {
throw 'An object with the set of interfaces for each state is required';
}
function trigger() {
if (typeof object.trigger == 'function') {
object.trigger.apply(object, arguments);
}
}
function applyState(state) {
let previousInterface = interfaces[currentState];
let newInterface = interfaces[state];
if (typeof newInterface == 'undefined') {
throw 'Invalid state: ' + state;
}
if (previousInterface) {
trigger('state:exit', currentState);
if (typeof previousInterface.onExitState == 'function') {
object.onExitState();
}
var property;
for (property in previousInterface) {
delete object[property];
}
delete object.onEnterState;
delete object.onExitState;
trigger('state:exited', currentState);
}
trigger('state:enter', state);
for (let newProperty in newInterface) {
object[newProperty] = newInterface[newProperty];
}
if (typeof newInterface.onEnterState == 'function') {
object.onEnterState();
}
trigger('state:entered', state);
}
function transitionTo(state) {
applyState(state);
currentState = state;
trigger('state:change');
}
function isCurrentState(state) {
// console.log(currentState);
return currentState === state;
}
if (typeof onInitialize == 'function') {
onInitialize(this, object);
}
transitionTo(initialState || 'default');
return {
is: isCurrentState,
transition: transitionTo
};
}