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

vivi/feat/design model #133

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
36 changes: 29 additions & 7 deletions Observable.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,27 @@ class ObserverList {
this.observerList = [];
}
add(observer) {
// todo add observer to list
this.observerList.push(observer);
}
remove(observer) {
// todo remove observer from list
remove(index) {
this.observerList.splice(index, 1);
}
count() {
// return observer list size
return this.observerList.length;
}
get(index) {
return this.observerList[index];
}
indexOf(observer) {
let index = -1;

this.observerList.forEach((item, curIndex) => {
if (item === observer) {
index = curIndex;
}
});

return index;
}
}

Expand All @@ -25,13 +39,21 @@ class Subject {
this.observers = new ObserverList();
}
addObserver(observer) {
// todo add observer
this.observers.add(observer);
}
removeObserver(observer) {
// todo remove observer
const index = this.observers.indexOf(observer);

this.observers.remove(index);
}
notify(...args) {
// todo notify
const len = this.observers.count();

for (let index = 0; index < len; index++) {
const observer = this.observers.get(index);

observer.update(...args);
}
}
}

Expand Down
34 changes: 31 additions & 3 deletions PubSub.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,46 @@ module.exports = class PubSub {

constructor() {
this.subscribers = {};
this.id = 0;
}

subscribe(type, fn) {
// todo subscribe
if (!this.subscribe[type]) this.subscribe[type] = [];

this.subscribe[type].push({
token: this.id,
func: fn,
});

this.id += 1;

return this.id;
}

unsubscribe(type, fn) {
// todo unsubscribe
let subscribe = this.subscribe[type];

if (!subscribe) return false;

const len = subscribe.length;

subscribe.forEach((item, index) => {
if (item.func === fn) subscribe.splice(index, 1);
});

return this;
}

publish(type, ...args) {
// todo publish
const subscribe = this.subscribe[type];

if (!subscribe) return false;

subscribe.forEach((item) => {
item.func(args[0]);
});

return this;
}

}