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
23 changes: 20 additions & 3 deletions Observable.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/*
* @Author: kael
* @Date: 2018-02-01 17:41:25
* @Author: kael
* @Date: 2018-02-01 17:41:25
* @Last Modified by: kael
* @Last Modified time: 2018-02-02 17:38:36
*/
Expand All @@ -11,13 +11,23 @@ class ObserverList {
}
add(observer) {
// todo add observer to list
this.observerList.push(observer);
}
remove(observer) {
// todo remove observer from list
if (this.observerList.includes(observer)) {
this.observerList = this.observerList.filter(item => item != observer);
}
}
count() {
// return observer list size
return this.observerList.length;
}
get(index){
return this.observerList[index]
}


}

class Subject {
Expand All @@ -26,13 +36,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
let count=this.observers.count()
for (let index = 0; index < count; index++) {
const obs = this.observers.get(index);
obs.update(...args)
}
}
}

module.exports = { Subject };
module.exports = { Subject };
12 changes: 12 additions & 0 deletions PubSub.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,26 @@ 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]) {
delete this.subscribers[type]
}
}

publish(type, ...args) {
// todo publish
if (this.subscribers[type]) {
this.subscribers[type].map(fn=>{
fn(...args)
})
}
}

}
2 changes: 2 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ describe('PubSub', () => {
let val = random();
ob.subscribe('add', (val) => sum += val);
ob.publish('add', val);
console.log('sum',sum,'val',val)
assert.ok(sum === val);
});

Expand Down Expand Up @@ -73,3 +74,4 @@ describe('Observable', () => {
assert.ok(ob.sum !== val);
});
});