class PubSub{
constructor(){
this.events = {}
}
subscribe(name,cb){
if(!this.events[name]) {
this.events[name] = [];
}
this.events[name].push(cb)
return () => this.unsubscribe()
}
publish(name,...args){
if(!this.events[name]) {
this.events[name] = [];
}
this.events[name].forEach(cb=>cb(...args))
}
unsubscribe(name,cb){
console.log('this.events', this.events)
if(this.events[name]) {
this.events[name] = this.events[name].filter(item=>item!==cb)
}
}
}
const ps = new PubSub();
const sub_off = ps.subscribe('login', (user)=>{
console.log('Hi', user.name)
})
ps.publish('login',{name:'zxj'})
sub_off();