diff --git a/Observable.js b/Observable.js index 03545cd..dc0e201 100644 --- a/Observable.js +++ b/Observable.js @@ -10,13 +10,27 @@ class ObserverList { this.observerList = []; } add(observer) { - // todo add observer to list + this.observerList.push(observer); } - remove(observer) { - // todo remove observer from list + remove(index) { + this.observerList.splice(index, 1); } count() { - // return observer list size + return this.observerList.length; + } + get(index) { + return this.observerList[index]; + } + indexOf(observer) { + let index = -1; + + this.observerList.forEach((item, curIndex) => { + if (item === observer) { + index = curIndex; + } + }); + + return index; } } @@ -25,13 +39,21 @@ class Subject { this.observers = new ObserverList(); } addObserver(observer) { - // todo add observer + this.observers.add(observer); } removeObserver(observer) { - // todo remove observer + const index = this.observers.indexOf(observer); + + this.observers.remove(index); } notify(...args) { - // todo notify + const len = this.observers.count(); + + for (let index = 0; index < len; index++) { + const observer = this.observers.get(index); + + observer.update(...args); + } } } diff --git a/PubSub.js b/PubSub.js index 0c7999e..9916f7a 100644 --- a/PubSub.js +++ b/PubSub.js @@ -9,18 +9,46 @@ module.exports = class PubSub { constructor() { this.subscribers = {}; + this.id = 0; } subscribe(type, fn) { - // todo subscribe + if (!this.subscribe[type]) this.subscribe[type] = []; + + this.subscribe[type].push({ + token: this.id, + func: fn, + }); + + this.id += 1; + + return this.id; } unsubscribe(type, fn) { - // todo unsubscribe + let subscribe = this.subscribe[type]; + + if (!subscribe) return false; + + const len = subscribe.length; + + subscribe.forEach((item, index) => { + if (item.func === fn) subscribe.splice(index, 1); + }); + + return this; } publish(type, ...args) { - // todo publish + const subscribe = this.subscribe[type]; + + if (!subscribe) return false; + + subscribe.forEach((item) => { + item.func(args[0]); + }); + + return this; } }