-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubject.js
31 lines (25 loc) · 922 Bytes
/
Subject.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
class Subject{
constructor(){
this.observers = {};
}
addObserver(eventType, observer, {once = false, priority = 0}={}){
if(!this.observers[eventType]){
this.observers[eventType] = [];
}
this.observers[eventType].push({ observer, once, priority });
this.observers[eventType].sort((a, b) => b.priority - a.priority);
}
removeObserver(eventType,observer) {
if(this.observers[eventType]){
this.observers[eventType] = this.observers[eventType].filter(obs => obs.observer !== observer);
}
}
notifyObservers(eventType,data) {
this.observers[eventType].forEach(obs => obs.observer.update(data));
}
triggerEvent(eventType, data) {
console.log(`Subject state has changed to: ${data}, for the event ${eventType}`);
this.notifyObservers(eventType, data);
}
}
module.exports = Subject;