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

李英泽-exercise17 #123

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
19 changes: 19 additions & 0 deletions Observable.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,23 @@ class ObserverList {
}
add(observer) {
// todo add observer to list
this.observerList.push(observer);
}
remove(observer) {
// todo remove observer from list
if(!observer){
return;
}
for(let i=0;i<this.observerList.length;i++){
let item = this.observerList[i]
if(item === observer){
this.observerList.splice(i, 1); //删除对于的订阅
}
}
}
count() {
// return observer list size
return this.observerList.length;
}
}

Expand All @@ -26,12 +37,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
if(this.observers.count() === 0){
return;
}
for(let i=0;i<this.observers.count();i++){
this.observers.observerList[i].update(...args);
}
}
}

Expand Down
25 changes: 25 additions & 0 deletions PubSub.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,39 @@ 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
let fns = this.subscribers[type]
if(!fns || !fns.length){
return;
}
if(!fn){
fns = []
}else{
for(let i=0;i<fns.length;i++){
let item = fns[i]
if(item === fn){
fns.splice(i, 1); //删除订阅
}
}
}
}

publish(type, ...args) {
// todo publish
let fns = this.subscribers[type]
if(!fns || !fns.length){
return;
}
for(let i=0;i<fns.length;i++){
fns[i].apply(this, args);
}
}

}