-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobserver-example.js
More file actions
58 lines (48 loc) · 1.21 KB
/
observer-example.js
File metadata and controls
58 lines (48 loc) · 1.21 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
class Subject {
observers = []
subscribe(observer) {
this.observers.push(observer)
}
unsubscribe(observer) {
this.observers = this.observers.filter(
obs => obs !== observer,
)
}
fire(action) {
this.observers.forEach(observer => {
observer.update(action)
})
}
}
class Observer {
constructor(state = 0) {
this.state = state
this.initialState = state
}
update({ type, payload }) {
switch (type) {
case 'INCREMENT':
this.state = ++this.state
break
case 'DECREMENT':
this.state = --this.state
break
case 'ADD':
this.state += payload
break
default:
this.state = this.initialState
}
}
}
const stream = new Subject()
const observer1 = new Observer()
const observer2 = new Observer(7)
stream.subscribe(observer1)
stream.subscribe(observer2)
stream.fire({ type: 'INCREMENT' }) // obs1.state = 1; obs2.state = 8
stream.fire({ type: 'INCREMENT' }) // obs1.state = 2; obs2.state = 9
stream.fire({ type: 'DECREMENT' }) // obs1.state = 1; obs2.state = 8
stream.fire({ type: 'ADD', payload: 3 }) // obs1.state = 4; obs2.state = 11
console.log(observer1.state) // 4
console.log(observer2.state) // 11