-
Notifications
You must be signed in to change notification settings - Fork 639
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
手写一个发布-订阅模式 #110
Labels
Comments
因该要加一个逻辑,不然该事件清除了,又调用解绑事件 |
执行一次把前面所有订阅的事件都卸载了,不太合适吧 |
/**
* https://blog.csdn.net/weixin_43792004/article/details/113442506
*/
//中间人 主题
class Dep {
constructor(callback) {
this.subs = []
this.callback = callback
}
addSub(sub) {
this.subs.push(sub)
return this
}
notify() {
this.subs.forEach(item=>item.update(this.callback))
}
}
//订阅者
class Sub {
constructor(val) {
this.val = val
}
update(callback) {
this.val = callback(this.val);
console.log('this.val: ', this.val);
}
}
//发布者
class Pub {
constructor() {
this.deps = []
}
addDep(dep) {
this.deps.push(dep)
}
removeDep(dep) {
let index = this.deps.indexOf(dep)
if(index!==-1) {
this.deps.splice(index,1)
return true
}
return false
}
publish(dep) {
this.deps.forEach(item=>item===dep&&item.notify())
}
}
let dep1 = new Dep(item=>item*item)
let sub1 = new Sub(3)
dep1.addSub(sub1)
let pub1 = new Pub()
pub1.addDep(dep1)
pub1.publish(dep1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: