class Subscribe{
constructor(){
// 维护注册列表
this.list = []
}
//
on(name,user,fn){
this.list.push({
"name":name,
"user":user,
"fn":fn
})
console.log(user + "订阅了" + name)
}
off(name,user){
// 遍历删除,达到取消订阅效果
this.list.forEach((item,index)=>{
if(item.name == name && item.user == user){
this.list.splice(index,1)
}
})
}
emit(name,content){
// 触发事件
this.list.forEach(item=>{
if(item.name = name){
console.log("给" + item.user + "发信息")
item.fn(content)
}
})
}
}
let subscribe = new Subscribe();
subscribe.on(
"湖人",
"wuyz",
function(content){
console.log("lbjmvp")
console.log(content)
})
subscribe.emit("湖人","hhh")
subscribe.off("湖人","wuyz")
subscribe.emit("湖人","hhh")
————————————————————————————————————————————————————————
class Subscribe {
constructor () {
this.list = []
}
on (id, name, fn) {
const index = this.list.find(v => v.id === id)
if (index) {
console.log('订阅ID重复');
return
}
this.list.push({id, name, fn})
}
emit (name, params) {
const current = this.list.find(v => v.name === name)
if (current) {
current.fn(params)
}
}
off (id) {
const index = this.list.findIndex(v => v.id === id)
if (index > -1) {
this.list.splice(index, 1)
}
}
}
const subscribe = new Subscribe()
subscribe.on(1, 'input', (params) => {
console.log('input', params);
})
subscribe.on(1, 'input', (params) => {
console.log('input', params);
})
subscribe.on(2, 'input2', (params) => {
console.log('input2', params);
})
subscribe.emit('input2', {name: 'HHHHH222', age: '21'})
subscribe.emit('input', {name: 'HHHHH1111', age: '11'})
JS发布订阅模式
最新推荐文章于 2024-08-15 22:33:35 发布