From dc5110bc1c7f8ebc3be48d07e2e94e614782b567 Mon Sep 17 00:00:00 2001 From: herott <294963786@qq.com> Date: Thu, 15 Aug 2019 23:15:15 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E7=BB=83=E4=B9=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Observable.js | 15 +++++++++++++++ PubSub.js | 24 ++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/Observable.js b/Observable.js index 03545cd..49e3e97 100644 --- a/Observable.js +++ b/Observable.js @@ -11,12 +11,22 @@ class ObserverList { } add(observer) { // todo add observer to list + this.observerList.push(observer) } remove(observer) { // todo remove observer from list + let inx = this.observerList.indexOf(observer) + if (inx > -1) { + this.observerList.splice(inx, 1) + return true + } else { + return '没有该观察者' + } + } count() { // return observer list size + return this.observerList.length } } @@ -26,12 +36,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 && observer.update(...args) + }) } } diff --git a/PubSub.js b/PubSub.js index 0c7999e..bf96c7b 100644 --- a/PubSub.js +++ b/PubSub.js @@ -13,14 +13,38 @@ module.exports = class PubSub { subscribe(type, fn) { // todo subscribe + this.subscribers[type] = this.subscribers[type] || [] + // 增加监听事件 + this.subscribers[type].push(fn) } unsubscribe(type, fn) { // todo unsubscribe + // 未监听该事件 + let ary = this.subscribers[type] + if (!ary) { + return '未监听该类型的事件' + } + // 解除该监听事件 + let inx = ary.indexOf(fn) + if (inx > -1) { + ary.splice(inx, 1) + return true + } else { + return '该类型上没有该事件' + } } publish(type, ...args) { // todo publish + let ary = this.subscribers[type] + if (!ary) { + return + } + // 触发该订阅事件 + ary.forEach(fn => { + fn(...args) + }) } }