From 3f992618bde7a65e016b787fc72968857770bb06 Mon Sep 17 00:00:00 2001 From: zhengwei Date: Tue, 20 Nov 2018 22:20:28 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A7=82=E5=AF=9F=E8=80=85=E6=A8=A1=E5=BC=8F&?= =?UTF-8?q?=E5=8F=91=E5=B8=83=E8=AE=A2=E9=98=85=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Observable.js | 19 +++++++++++++++++++ PubSub.js | 21 +++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/Observable.js b/Observable.js index 03545cd..457b51d 100644 --- a/Observable.js +++ b/Observable.js @@ -11,12 +11,25 @@ class ObserverList { } add(observer) { // todo add observer to list + this.observerList.push(observer); } remove(observer) { // todo remove observer from list + for (var i = 0; i < this.observerList.length; i++) { + if (this.observerList[i] == observer) { + this.observerList.splice(i, 1); + return this.observerList; + } + } } count() { // return observer list size + return this.observerList.length; + } + get(index) { + if (index > -1 && index < this.observerList.length) { + return this.observerList[index]; + } } } @@ -26,12 +39,18 @@ class Subject { } addObserver(observer) { // todo add observer + this.observers.add(observer); } removeObserver(observer) { // todo remove observer + this.observers.remove(observer); } notify(...args) { // todo notify + var count = this.observers.count(); + for (var i = 0; i < count; i++) { + this.observers.get(i).update(...args); + } } } diff --git a/PubSub.js b/PubSub.js index 0c7999e..e6179dc 100644 --- a/PubSub.js +++ b/PubSub.js @@ -13,14 +13,35 @@ 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; + } + + for (var i = 0; i < this.subscribers[type].length; i++) { + if (this.subscribers[type][i] === fn) { + this.subscribers[type].splice(i, 1); + return this.subscribers[type]; + } + } + } publish(type, ...args) { // todo publish + if (!this.subscribers[type]) { + return false; + } + + this.subscribers[type].forEach(subscriber => subscriber(...args)) + } }