-
Notifications
You must be signed in to change notification settings - Fork 1
/
statemachine.js
60 lines (46 loc) · 1.11 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
// 定义 (状态 -> 动作 -> 下一个状态)的集合
const machine = {
currentState: 'login form',
states: {
'login form': {
submit: 'loading'
},
'loading': {
success: 'profile',
failure: 'error'
},
'profile': {
viewProfile: 'profile',
logout: 'login form'
},
'error': {
tryAgain: 'loading'
}
}
}
const input = function (name) {
const state = machine.currentState;
if (machine.states[state][name]) {
machine.currentState = machine.states[state][name];
}
console.log(`${ state } + ${ name } --> ${ machine.currentState }`);
}
input('tryAgain');
// login form + tryAgain --> login form
input('submit');
// login form + submit --> loading
input('submit');
// loading + submit --> loading
input('failure');
// loading + failure --> error
input('submit');
// error + submit --> error
input('tryAgain');
// error + tryAgain --> loading
input('success');
// loading + success --> profile
input('viewProfile');
// profile + viewProfile --> profile
input('logout');
// profile + logout --> login form
---------------------