含义
1.发布者提供可发布的数据
2.订阅者 - 接收事件
3.当数据变更时,发布者根据 数据关联的订阅者,通知订阅者
好处:为了解耦,使模块之间的关联不那么紧密
举例
实现event.on、event.emit、event.on
- event.emit(eventName, ()=>{}),发布者发布消息,会触发所有订阅该事件的订阅者
- event.on(eventName, ()=>{}), 订阅事件,可联系订阅事件,订阅不同的事件
- event.off(eventName, ()=>{}),移除事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div>发布订阅模式</div>
<script>
let event = (function () {
let eventObjs = {};
return {
// 订阅者,接收事件
on: function (type, handler) {
// type: 事件名称 handle:事件函数
(eventObjs[type] || (eventObjs[type] = [])).push(handler);
},
// 发布者:触发事件
emit: function (type) {
// 获取参数,除type
let args = Array.prototype.slice.call(arguments, 1);
let funcList = eventObjs[type] || [];
funcList.forEach((func) => {
func.apply(null, args);
});
},
// 关闭事件
// 1.没有参数,移除所有事件
// 2.有一个参数,移除该事件的所有函数
// 3.有两个参数,移除该事件某个函数
off: function (type, handler) {
if (!type) {
eventObjs = {};
} else if (arguments.length === 1) {
eventObjs[type] = [];
} else {
let funcList = eventObjs[type];
funcList.forEach((func, index) => {
if (func === handler) {
funcList.splice(index, 1);
}
});
}
},
};
})();
</script>
</body>
</html>