/*
$on("event",fn);
$emit("event",parms...)
$off("event") 事件的所抛发的函数全部关掉
$off("event",fn) 关掉事件所抛发的发你函数
*/
const eventList = {};
const $on = (eventName, eventFunction) => {
if (!eventList[eventName]) {
eventList[eventName] = []
}
eventList[eventName].push(eventFunction)
}
const $emit = (eventName, ...params) => {
if (eventList[eventName]) {
let arr = eventList[eventName];
arr.forEach(eventFunction => {
eventFunction(...params)
});
}
}
const $off = (eventName, eventFunction) => {
if (eventList[eventName]) {
if (eventFunction) {
let flag = eventList[eventName].includes(eventFunction);
if(flag){
let index = eventList[eventName].indexOf(eventFunction)
eventList[eventName].splice(index, 1);
}
} else {
eventList[eventName].length = 0;
}
}
}
$on("sss", fn1);
$off("sss");
$emit("sss", 1, 2, 3);
function fn1(a, b, c) {
console.log("fn1执行了");
console.log(a, b)
}
vue发布订阅模式封装
最新推荐文章于 2024-04-17 14:17:09 发布