forked from FE-star/exercise17
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObservable.js
More file actions
50 lines (47 loc) · 1007 Bytes
/
Observable.js
File metadata and controls
50 lines (47 loc) · 1007 Bytes
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
/*
* @Author: kael
* @Date: 2018-02-01 17:41:25
* @Last Modified by: kael
* @Last Modified time: 2018-02-02 17:38:36
*/
class ObserverList {
constructor() {
this.observerList = [];
}
add(observer) {
// todo add observer to list
this.observerList.push(observer);
}
remove(observer) {
// todo remove observer from list
let i = this.observerList.indexOf(observer);
this.observerList.splice(i, 1);
}
count() {
// return observer list size
return this.observerList.length;
}
get(index) {
return this.observerList[index];
}
}
class Subject {
constructor() {
this.observers = new ObserverList();
}
addObserver(observer) {
// todo add observer
this.observers.add(observer);
}
removeObserver(observer) {
// todo remove observer
this.observers.remove(observer);
}
notify(...args) {
// todo notify
this.observers.observerList.forEach(ob => {
ob.update(...args);
});
}
}
module.exports = { Subject };