-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathexample.ts
More file actions
81 lines (61 loc) · 2.15 KB
/
Copy pathexample.ts
File metadata and controls
81 lines (61 loc) · 2.15 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
/// <reference path="../dist/typestate.d.ts" />
/// <reference path="knockout.d.ts" />
// Let's model the states of an elevator
// Define an Enum with all possible valid states
enum Elevator {
DoorsOpened,
DoorsClosed,
Moving
}
// Construct the FSM with the inital state, in this case the elevator starts with its doors opened
var fsm = new typestate.FiniteStateMachine<Elevator>(Elevator.DoorsOpened);
// Declare the valid state transitions to model your system
// Doors can go from opened to closed, and vice versa
fsm.from(Elevator.DoorsOpened).to(Elevator.DoorsClosed);
fsm.from(Elevator.DoorsClosed).to(Elevator.DoorsOpened);
// Once the doors are closed the elevator may move
fsm.from(Elevator.DoorsClosed).to(Elevator.Moving);
// When the elevator reaches its destination, it may stop moving
fsm.from(Elevator.Moving).to(Elevator.DoorsClosed);
var handsInDoor = false;
// Listen for transitions to DoorsClosed, if the callback returns false the transition is canceled.
fsm.onEnter(Elevator.DoorsClosed, ()=>{
if(handsInDoor){
return false;
}
return true;
});
class ViewModel {
constructor() { }
public HandsInDoor: KnockoutObservable<boolean> = ko.observable<boolean>()
public CurrentState: KnockoutObservable<Elevator> = ko.observable<Elevator>(fsm.currentState)
public Move() {
fsm.go(Elevator.Moving);
this.CurrentState(fsm.currentState);
}
public Open() {
fsm.go(Elevator.DoorsOpened);
this.CurrentState(fsm.currentState);
}
public Close() {
fsm.go(Elevator.DoorsClosed);
this.CurrentState(fsm.currentState);
}
public CanMove: KnockoutComputed<boolean> = ko.computed<boolean>(() => {
this.CurrentState();
return fsm.canGo(Elevator.Moving);
});
public CanOpen: KnockoutComputed<boolean> = ko.computed<boolean>(() => {
this.CurrentState();
return fsm.canGo(Elevator.DoorsOpened);
});
public CanClose: KnockoutComputed<boolean> = ko.computed<boolean>(() => {
this.CurrentState();
return fsm.canGo(Elevator.DoorsClosed);
});
}
var vm = new ViewModel();
vm.HandsInDoor.subscribe((val) => {
handsInDoor = val;
});
ko.applyBindings(vm);