<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>发布订阅模式</title>
</head>
<body>
<button type="button">点击我啦!</button>
<script type="text/javascript">
class Sub{
constructor() {
this.$pond=[] //创建一个事件池
}
// 向事件池添加一个方法
add(fun){
let flag=this.$pond.some(item=>{ //去重 不能向事件池中 添加同一个方法
return item===fun
})
!flag ? this.$pond.push(fun) : null
}
// 删除事件池中的方法
remove(fun){
let $pond=this.$pond;
for(let i=0;i<$pond.length;i++){
let item=$pond[i]
if(item === fun){
$pond[i] = null
break
}
}
}
// 通知 事件池中的方法一次执行
fire(...args){
let $pond=this.$pond;
for(let i=0;i<$pond.length;i++){
let item=$pond[i]
if(typeof item !== "function"){ //事件池中的方法必须是函数
$pond.splice(i,1)
i--;
continue
}
item(...args)
// item.call(this,...args)
}
}
}
let pond=new Sub()
document.querySelector("button").onclick=function(ev){
pond.fire(ev)
}
function fn1(){
console.log(1)
}
function fn2(){
console.log(2)
}
function fn3(){
console.log(3)
}
function fn4(ev){
console.log(ev)
}
pond.add(fn1)
pond.add(fn2)
pond.add(fn3)
pond.add(fn4)
</script>
</body>
</html>
发布订阅模式 简单应用
最新推荐文章于 2022-10-14 11:25:19 发布