-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobserver.js
60 lines (48 loc) · 1.23 KB
/
observer.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
/**
* Observer
*
* Observer is a behavioral design pattern that lets you define
* a subscription mechanism to notify multiple objects about any events
* that occur to the object they're observing. In other words,
* it allows objects to be notified automatically
* of any changes in state of another object.
*/
// observable
class Subject {
observers = []
addObserver(observer) {
this.observers.push(observer)
}
removeObserver(observer) {
this.observers = this.observers.filter(
obs => obs !== observer,
)
}
notify(data) {
this.observers.forEach(observer =>
observer.update(data),
)
}
}
// observer
class Observer {
constructor(name) {
this.name = name
}
update(data) {
console.log(
`"${this.name}" recieved a notification: "${data}"`,
)
}
}
const subject = new Subject()
const observer1 = new Observer('Observer 1')
const observer2 = new Observer('Observer 2')
subject.addObserver(observer1)
subject.addObserver(observer2)
subject.notify('Change 1')
// "Observer 1" recieved a notification: "Change 1"
// "Observer 2" recieved a notification: "Change 1"
subject.removeObserver(observer1)
subject.notify('Change 2')
// "Observer 2" recieved a notification: "Change 2"