diff --git a/Observable.js b/Observable.js index 03545cd..abed522 100644 --- a/Observable.js +++ b/Observable.js @@ -11,12 +11,20 @@ class ObserverList { } add(observer) { // todo add observer to list + this.observerList.push(observer); } remove(observer) { // todo remove observer from list + this.observerList = this.observerList.filter(item => item !== observer); } count() { // return observer list size + return this.observerList.length; + } + get(index) { + if (index > -1 && index < this.observerList.length) { + return this.observerList[index]; + } } } @@ -26,12 +34,19 @@ 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 i = 0, + len = this.observers.count(); + for (i = 0; i < len; i++) { + this.observers.get(i).update(...args); + } } } diff --git a/PubSub.js b/PubSub.js index 0c7999e..bb9358b 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: fn }); } unsubscribe(type, fn) { // todo unsubscribe + if (this.subscribers[type]) { + var len = this.subscribers[type].length; + for (var i = 0; i < len; i++) { + if (this.subscribers[type][i].fn === fn) { + this.subscribers[type].splice(i, 1); + break; + } + } + } } publish(type, ...args) { // todo publish + if (!this.subscribers[type]) { + return false; + } + var typeSubs = this.subscribers[type], + len = typeSubs ? typeSubs.length : 0; + while (len--) { + typeSubs[len].fn(...args); + } } }