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) + }) } }