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
15 changes: 15 additions & 0 deletions Observable.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* @Date: 2018-02-01 17:41:25
* @Last Modified by: kael
* @Last Modified time: 2018-02-02 17:38:36
* 觀察者
*/

class ObserverList {
Expand All @@ -11,12 +12,20 @@ class ObserverList {
}
add(observer) {
// todo add observer to list
this.observerList.push(observer);
}
remove(observer) {
// todo remove observer from list
this.observerList.forEach((item,index)=>{
item== observer && this.observerList.splice(index,1);
})
}
get(i){
return this.observerList[i];
}
count() {
// return observer list size
return this.observerList.length;
}
}

Expand All @@ -26,12 +35,18 @@ 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 length = this.observers.count();
for(var i =0; i<length;i++){
this.observers.get(i).update(...args)
}
}
}

Expand Down
14 changes: 14 additions & 0 deletions PubSub.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* @Date: 2018-02-01 17:41:25
* @Last Modified by: kael
* @Last Modified time: 2018-02-02 17:39:45
* 發佈/訂閲模式
*/

module.exports = class PubSub {
Expand All @@ -13,14 +14,27 @@ module.exports = class PubSub {

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

unsubscribe(type, fn) {
// todo unsubscribe
if (!this.subscribers[type]) {
return false
}
this.subscribers[type] = undefined
}

publish(type, ...args) {
// todo publish
if (!this.subscribers[type]) {
return false
}
this.subscribers[type](...args)
}

}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha"
"test": "mocha -g Observable"
},
"repository": {
"type": "git",
Expand Down
5 changes: 5 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ describe('PubSub', () => {
ob.unsubscribe('add', add);
ob.publish('add', val);
assert.ok(sum !== val);

ob.subscribe('add', (val)=> val++);
ob.publish('add', val);
assert.ok( ++val === val);

});
});

Expand Down