From ea96238157e14a5c71647d79f9f2af2138848166 Mon Sep 17 00:00:00 2001 From: hutn <32947142+hutn@users.noreply.github.com> Date: Sat, 17 Nov 2018 21:56:43 +0800 Subject: [PATCH 1/2] Update Observable.js --- Observable.js | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/Observable.js b/Observable.js index 03545cd..b20be57 100644 --- a/Observable.js +++ b/Observable.js @@ -11,12 +11,21 @@ class ObserverList { } add(observer) { // todo add observer to list + this.observerList.push(observer); } remove(observer) { // todo remove observer from list + let index = 0; + this.observerList.forEach(element => { + if(element === observer){ + this.observerList.splice(index, 1) + } + index++; + }); } count() { // return observer list size + return this.observerList.length; } } @@ -26,13 +35,18 @@ class Subject { } addObserver(observer) { // todo add observer + this.observers.add(observer); } removeObserver(observer) { // todo remove observer + this.observers.remove( this.observers.observerList.indexOf(observer) ); } notify(...args) { // todo notify + this.observers.observerList.map( observer => { + observer.update.call( observer, ...args); + }) } } -module.exports = { Subject }; \ No newline at end of file +module.exports = { Subject }; From 06eda6ac2e9295a7763271cdabf798c257d4cf00 Mon Sep 17 00:00:00 2001 From: hutn <32947142+hutn@users.noreply.github.com> Date: Sat, 17 Nov 2018 22:01:07 +0800 Subject: [PATCH 2/2] Update PubSub.js --- PubSub.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/PubSub.js b/PubSub.js index 0c7999e..8052230 100644 --- a/PubSub.js +++ b/PubSub.js @@ -13,14 +13,37 @@ module.exports = class PubSub { subscribe(type, fn) { // todo subscribe + if( !this.subscribers[type] ){ + this.subscribers[type] = []; + } + this.subscribers[type].push(fn); } unsubscribe(type, fn) { // todo unsubscribe + if (!this.subscribers[type]) { + return false; + } else { + let queue = this.subscribers[type]; + let index = 0; + queue.forEach(element => { + if(element === fn){ + queue.splice(index, 1) + } + index++; + }); + } } publish(type, ...args) { // todo publish + if (!this.subscribers[type]) { + return false; + } else { + this.subscribers[type].forEach(element => { + element.apply(this, args) + }); + } } }