From 0ae8a91098d56bd214afddbbac6519018d2cc54d Mon Sep 17 00:00:00 2001 From: hongyongbo Date: Mon, 19 Nov 2018 14:07:21 +0800 Subject: [PATCH] =?UTF-8?q?feat=EF=BC=9Afinish=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Observable.js | 23 ++++++++++++++++++++--- PubSub.js | 12 ++++++++++++ test/test.js | 2 ++ 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/Observable.js b/Observable.js index 03545cd..e5b813b 100644 --- a/Observable.js +++ b/Observable.js @@ -1,6 +1,6 @@ /* - * @Author: kael - * @Date: 2018-02-01 17:41:25 + * @Author: kael + * @Date: 2018-02-01 17:41:25 * @Last Modified by: kael * @Last Modified time: 2018-02-02 17:38:36 */ @@ -11,13 +11,23 @@ class ObserverList { } add(observer) { // todo add observer to list + this.observerList.push(observer); } remove(observer) { // todo remove observer from list + if (this.observerList.includes(observer)) { + this.observerList = this.observerList.filter(item => item != observer); + } } count() { // return observer list size + return this.observerList.length; } + get(index){ + return this.observerList[index] + } + + } class Subject { @@ -26,13 +36,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 + let count=this.observers.count() + for (let index = 0; index < count; index++) { + const obs = this.observers.get(index); + obs.update(...args) + } } } -module.exports = { Subject }; \ No newline at end of file +module.exports = { Subject }; diff --git a/PubSub.js b/PubSub.js index 0c7999e..ba0a101 100644 --- a/PubSub.js +++ b/PubSub.js @@ -13,14 +13,26 @@ 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]) { + delete this.subscribers[type] + } } publish(type, ...args) { // todo publish + if (this.subscribers[type]) { + this.subscribers[type].map(fn=>{ + fn(...args) + }) + } } } diff --git a/test/test.js b/test/test.js index aab05a3..45ef5ff 100644 --- a/test/test.js +++ b/test/test.js @@ -18,6 +18,7 @@ describe('PubSub', () => { let val = random(); ob.subscribe('add', (val) => sum += val); ob.publish('add', val); + console.log('sum',sum,'val',val) assert.ok(sum === val); }); @@ -73,3 +74,4 @@ describe('Observable', () => { assert.ok(ob.sum !== val); }); }); +