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
57 lines (54 loc) · 1.16 KB
/
Observable.js
File metadata and controls
57 lines (54 loc) · 1.16 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
/*
* @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
if(!observer){
return;
}
for(let i=0;i<this.observerList.length;i++){
let item = this.observerList[i]
if(item === observer){
this.observerList.splice(i, 1); //删除对于的订阅
}
}
}
count() {
// return observer list size
return this.observerList.length;
}
}
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
if(this.observers.count() === 0){
return;
}
for(let i=0;i<this.observers.count();i++){
this.observers.observerList[i].update(...args);
}
}
}
module.exports = { Subject };