diff --git a/Observable.js b/Observable.js index 03545cd..cf36710 100644 --- a/Observable.js +++ b/Observable.js @@ -11,12 +11,19 @@ class ObserverList { } add(observer) { // todo add observer to list + this.observerList.push(observer); } remove(observer) { // todo remove observer from list + let index=this.observerList.indexOf(observer); + if(index>-1){ + this.observerList.splice(index,1); + } + } count() { // return observer list size + return this.observerList.length; } } @@ -26,13 +33,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 + + var observerCount = this.observers.count(); + for(var i=0; i < observerCount; i++){ + this.observers.observerList[i].update(...args); + } } } -module.exports = { Subject }; \ No newline at end of file +module.exports = { Subject }; diff --git a/PubSub.js b/PubSub.js index 0c7999e..b59fa37 100644 --- a/PubSub.js +++ b/PubSub.js @@ -13,14 +13,30 @@ 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; + const sub = this.subscribers[type]; + const idx = sub.indexOf(fn); + if (idx >= 0) { + sub.splice(idx, 1); + } } publish(type, ...args) { // todo publish + const sub = this.subscribers[type]; + if (!sub) return; + sub.forEach(fn => { + fn(...args); + }) } }