发布订阅模式 简单应用

<!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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值