diff --git a/Observable.js b/Observable.js index 03545cd..3546645 100644 --- a/Observable.js +++ b/Observable.js @@ -11,12 +11,19 @@ class ObserverList { } add(observer) { // todo add observer to list + this.observerList.push(observer) } remove(observer) { // todo remove observer from list + const matchIndex = this.observerList.findIndex(observer => observer === observer) + + if (matchIndex > -1) { + this.observerList.splice(matchIndex, 1) + } } count() { // return observer list size + return this.observerList.length } } @@ -26,12 +33,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 + this.observers.observerList.forEach(observer => { + observer.update(...args) + }); } } diff --git a/PubSub.js b/PubSub.js index 0c7999e..49d3928 100644 --- a/PubSub.js +++ b/PubSub.js @@ -12,15 +12,41 @@ module.exports = class PubSub { } subscribe(type, fn) { - // todo subscribe + if (!type || !fn) return; + if (!this.subscribers[type]) { + this.subscribers[type] = [] + } + + this.subscribers[type].push(fn) } unsubscribe(type, fn) { - // todo unsubscribe + if(!type) return + const subscribeFns = this.subscribers[type] + + if (!subscribeFns || subscribeFns.length === 0) return + + if(!fn) this.subscribers[type] = [] + + for (let i = 0, len = subscribeFns.length; i < len; i++) { + if (subscribeFns[i] === fn) { + subscribeFns.splice(i, 1) + return + } + } + } publish(type, ...args) { - // todo publish + if (!type) return + const subscribeFns = this.subscribers[type] + if (!subscribeFns || subscribeFns.length === 0) return + + if (subscribeFns.length === 1) return subscribeFns[0](...args) + + for (let i = 0, len = subscribeFns.length; i < len; i++) { + subscribeFns[i](...args) + } } }