Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Observable.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,25 @@ class ObserverList {
}
add(observer) {
// todo add observer to list
this.observerList.push(observer);
}
remove(observer) {
// todo remove observer from list
for (var i = 0; i < this.observerList.length; i++) {
if (this.observerList[i] == observer) {
this.observerList.splice(i, 1);
return this.observerList;
}
}
}
count() {
// return observer list size
return this.observerList.length;
}
get(index) {
if (index > -1 && index < this.observerList.length) {
return this.observerList[index];
}
}
}

Expand All @@ -26,12 +39,18 @@ 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 count = this.observers.count();
for (var i = 0; i < count; i++) {
this.observers.get(i).update(...args);
}
}
}

Expand Down
21 changes: 21 additions & 0 deletions PubSub.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

unsubscribe(type, fn) {
// todo unsubscribe
if (!this.subscribers[type]) {
return false;
}

for (var i = 0; i < this.subscribers[type].length; i++) {
if (this.subscribers[type][i] === fn) {
this.subscribers[type].splice(i, 1);
return this.subscribers[type];
}
}

}

publish(type, ...args) {
// todo publish
if (!this.subscribers[type]) {
return false;
}

this.subscribers[type].forEach(subscriber => subscriber(...args))

}

}