Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Observable.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,16 @@ class ObserverList {
}
add(observer) {
// todo add observer to list
this.observerList.push(observer);
}
remove(observer) {
// todo remove observer from list
const idx = this.observerList.indexOf(observer);
this.observerList.splice(idx, 1);
}
count() {
// return observer list size
return this.observerList.length;
}
}

Expand All @@ -26,12 +30,17 @@ class Subject {
}
addObserver(observer) {
// todo add observer
this.observers.add(observer)
}
removeObserver(observer) {
// todo remove observer
this.observers.remove(observer)
}
notify(...args) {
// todo notify
for(let i = 0; i < this.observers.count(); i++) {
this.observers.observerList[i].update(...args)
}
}
}

Expand Down
17 changes: 17 additions & 0 deletions PubSub.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,31 @@ module.exports = class PubSub {

subscribe(type, fn) {
// todo subscribe
let sub = this.subscribers[type]
if (sub) {
sub.push(fn);
} else {
this.subscribers[type] = [fn];
}
}

unsubscribe(type, fn) {
// todo unsubscribe
if (!this.subscribers[type]) return;
const sub = this.subscribers[type];
const idx = sub.indexOf(fn);
if (idx >= 0) {
sub.splice(idx, 1);
}
}

publish(type, ...args) {
// todo publish
const sub = this.subscribers[type];
if (!sub) return;
sub.forEach(fn => {
fn(...args);
})
}

}