Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

passed #107

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
22 changes: 14 additions & 8 deletions Observable.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,31 +7,37 @@

class ObserverList {
constructor() {
this.observerList = [];
this.observerList = []
}
add(observer) {
// todo add observer to list
return this.observerList.push(observer)
}
remove(observer) {
// todo remove observer from list
for(var i=0,len=this.count();i<len;i++)
if(this.observerList[i]===observer)
return this.observerList.splice(i, 1)
}
count() {
// return observer list size
return this.observerList.length
}
get(i){
return this.observerList[i]
}
}

class Subject {
constructor() {
this.observers = new ObserverList();
this.observers = new ObserverList()
}
addObserver(observer) {
// todo add observer
this.observers.add(observer)
}
removeObserver(observer) {
// todo remove observer
this.observers.remove(observer)
}
notify(...args) {
// todo notify
for (var i = 0, len = this.observers.count(); i < len; i++)
this.observers.get(i).update(...args)
}
}

Expand Down
28 changes: 25 additions & 3 deletions PubSub.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,37 @@ 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
for (var type in this.subscribers) {
if (this.subscribers[type]) {
for (var i = 0, j = this.subscribers[type].length; i < j; i++) {
if (this.subscribers[type][i] === fn) {
this.subscribers[type].splice(i, 1);
}
}
}
}
return this;
}

publish(type, ...args) {
// todo publish
if (!this.subscribers[type]) {
return false;
}
var subscribers = this.subscribers[type],
len = subscribers ? subscribers.length : 0;

while (len--) {
subscribers[len].call(type, ...args);
}

return this;
}

}