<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button id="button" type="button">按钮</button>
<button id="button2" type="button">取消监听</button>
</body>
</html>
<script type="text/javascript">
class PubSub {
constructor() {
this.eventList = []
}
static createId() {
return Symbol(Math.random())
}
static off(names, by) {
names.forEach(tragets => {
const combineTargets = Array.isArray(tragets) ? [...tragets] : [tragets]
combineTargets.forEach(target => {
this.eventList = this.eventList.filter(e => e[by] !== target)
})
})
}
on(name, fn) {
const id = this.constructor.createId()
const e = {
name,
fn,
id
}
this.eventList.push(e)
return id
原生js实现发布订阅PubSub
最新推荐文章于 2022-11-07 15:05:09 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)