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 @@ -11,12 +11,22 @@ class ObserverList {
}
add(observer) {
// todo add observer to list
this.observerList.push(observer)
}
remove(observer) {
// todo remove observer from list
let inx = this.observerList.indexOf(observer)
if (inx > -1) {
this.observerList.splice(inx, 1)
return true
} else {
return '没有该观察者'
}

}
count() {
// return observer list size
return this.observerList.length
}
}

Expand All @@ -26,12 +36,17 @@ class Subject {
}
addObserver(observer) {
// todo add observer
this.observers.add(observer)
}
removeObserver(observer) {
// todo remove observer
this.observers.remove(observer)
}
notify(...args) {
// todo notify
this.observers.observerList.forEach(observer => {
observer.update && observer.update(...args)
})
}
}

Expand Down
24 changes: 24 additions & 0 deletions PubSub.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,38 @@ 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
// 未监听该事件
let ary = this.subscribers[type]
if (!ary) {
return '未监听该类型的事件'
}
// 解除该监听事件
let inx = ary.indexOf(fn)
if (inx > -1) {
ary.splice(inx, 1)
return true
} else {
return '该类型上没有该事件'
}
}

publish(type, ...args) {
// todo publish
let ary = this.subscribers[type]
if (!ary) {
return
}
// 触发该订阅事件
ary.forEach(fn => {
fn(...args)
})
}

}