From f6866c97d05576a7378258a6a70e9e448516a389 Mon Sep 17 00:00:00 2001 From: zx Date: Fri, 9 Aug 2019 16:05:20 +0800 Subject: [PATCH] wancheng --- Observable.js | 19 +++++++++++++++++++ PubSub.js | 7 +++++++ 2 files changed, 26 insertions(+) diff --git a/Observable.js b/Observable.js index 03545cd..71d937e 100644 --- a/Observable.js +++ b/Observable.js @@ -11,12 +11,23 @@ class ObserverList { } add(observer) { // todo add observer to list + return this.observerList.push(observer); } remove(observer) { // todo remove observer from list + const index = this.observerList.indexOf(observer); + if (index !== -1) { + this.observerList.splice(index, 1); + } } count() { // return observer list size + return this.observerList.length + } + get(index){ + if( index > -1 && index < this.observerList.length ){ + return this.observerList[ index ]; + } } } @@ -26,12 +37,20 @@ class Subject { } addObserver(observer) { // todo add observer + this.observers.add(observer); } removeObserver(observer) { // todo remove observer + this.observers.remove(observer); } notify(...args) { // todo notify + if(this.observers.count() > 0) { + const length = this.observers.count(); + for (let i = 0; i < length; i++) { + this.observers.get(i).update(...args); + } + } } } diff --git a/PubSub.js b/PubSub.js index 0c7999e..c4b7ecb 100644 --- a/PubSub.js +++ b/PubSub.js @@ -13,14 +13,21 @@ module.exports = class PubSub { subscribe(type, fn) { // todo subscribe + let topic = this.subscribers[type]; + if (!topic) { + this.subscribers[type] = []; + } + this.subscribers[type].push(fn); } unsubscribe(type, fn) { // todo unsubscribe + delete this.subscribers[type]; } publish(type, ...args) { // todo publish + this.subscribers[type] && this.subscribers[type].forEach(fn => fn(...args)); } }