-
Notifications
You must be signed in to change notification settings - Fork 75
/
Observer.js
79 lines (67 loc) · 1.78 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
'use strict';
class Subject {
constructor() {
console.log('Subject Class created');
}
attach(observer) {
this.observers.push(observer);
console.log('Subject.attach invoked');
}
dettach(observer) {
console.log('Subject.dettach invoked');
for (var i in this.observers) {
if (this.observers[i] === observer) {
this.observers.splice(i, 1);
}
}
}
notify() {
console.log('Subject.notify invoked');
for (var i in this.observers) {
this.observers[i].update(this);
}
}
}
class ConcreteSubject extends Subject {
constructor() {
super();
this.subjectState = null;
this.observers = [];
console.log('ConcreteSubject Class created');
}
getState() {
console.log('ConcreteSubject.getState invoked');
return this.subjectState;
}
setState(state) {
console.log('ConcreteSubject.setState invoked');
this.subjectState = state;
this.notify();
}
}
class Observer {
constructor() {
console.log('Observer Class created');
}
update() {
console.log('Observer.update invoked');
}
}
class ConcreteObserver extends Observer {
constructor() {
super();
this.observerState = '';
console.log('ConcreteObserver Class created');
}
update(Subject) {
console.log('ConcreteObserver.update invoked');
this.observerState = Subject.getState();
console.log('Observer new state: ' + this.observerState);
}
}
var observer1 = new ConcreteObserver();
var observer2 = new ConcreteObserver();
var subject = new ConcreteSubject();
subject.attach(observer1);
subject.attach(observer2);
subject.setState('state 1');