-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
63 lines (51 loc) · 1.27 KB
/
index.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
/**
* Observer Pattern
*/
// The Observer List
function ObserverList() {
this.observerList = [];
}
ObserverList.prototype.add = function(obj) {
this.observerList.push(obj);
};
ObserverList.prototype.count = function(obj) {
return this.observerList.length;
};
ObserverList.prototype.get = function(index) {
if(index > -1 && index < this.observerList.length) {
return this.observerList[index];
}
};
ObserverList.prototype.indexOf = function(obj) {
for(let i = 0; i < this.observerList.length; i++) {
if(obj === this.obj[i]) {
return i;
}
}
return -1;
};
ObserverList.prototype.removeAt = function(index) {
this.observerList.splice(index, 1);
};
// The Subject
function Subject() {
this.observers = new ObserverList();
}
Subject.prototype.addObserver = function(observer) {
this.observers.add(observer);
};
Subject.prototype.removeObserver = function(observer) {
this.observers.removeAt(this.observers.indexOf(observer));
};
Subject.prototype.notify = function(context) {
const count = this.observers.count();
for(let i = 0; i < count; i++) {
this.observers.get(i).update(context);
}
}
// The Observer
function Observer() {
this.update = function() {
// ...
}
}