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

提交答案 #131

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
24 changes: 16 additions & 8 deletions Observable.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,28 @@
/*
* @Author: kael
* @Date: 2018-02-01 17:41:25
* @Last Modified by: kael
* @Last Modified time: 2018-02-02 17:38:36
* @Last Modified by: mt
* @Last Modified time: 2019-08-10 23:29:08
*/

class ObserverList {
constructor() {
this.observerList = [];
}
add(observer) {
// todo add observer to list
this.observerList.push(observer);
}
remove(observer) {
// todo remove observer from list
const index = this.observerList.indexOf(observer);
if (index !== -1) {
this.observerList.splice(index, 1);
}
}
count() {
// return observer list size
return this.observerList.length;
}
iterate(cb) {
this.observerList.forEach(cb);
}
}

Expand All @@ -25,13 +31,15 @@ class Subject {
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
this.observers.iterate(function (observer) {
observer.update(...args);
});
}
}

Expand Down
24 changes: 19 additions & 5 deletions PubSub.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/*
* @Author: kael
* @Date: 2018-02-01 17:41:25
* @Last Modified by: kael
* @Last Modified time: 2018-02-02 17:39:45
* @Last Modified by: mt
* @Last Modified time: 2019-08-10 23:03:01
*/

module.exports = class PubSub {
Expand All @@ -12,15 +12,29 @@ module.exports = class PubSub {
}

subscribe(type, fn) {
// todo subscribe
this.subscribers[type] = this.subscribers[type] || [];
this.subscribers[type].push(fn);
}

unsubscribe(type, fn) {
// todo unsubscribe
if (this.subscribers[type] === undefined) {
throw new Error('unknown type');
}

const index = this.subscribers[type].indexOf(fn);
if (index !== -1) {
this.subscribers[type].splice(index, 1);
}
}

publish(type, ...args) {
// todo publish
if (this.subscribers[type] === undefined) {
throw new Error('unknown type');
}

this.subscribers[type].forEach(fn => {
fn.apply(this, args);
});
}

}