diff --git a/Observable.js b/Observable.js index 03545cd..909d85d 100644 --- a/Observable.js +++ b/Observable.js @@ -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; } } @@ -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) + } } } diff --git a/PubSub.js b/PubSub.js index 0c7999e..156f82c 100644 --- a/PubSub.js +++ b/PubSub.js @@ -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); + }) } }