const center = {};
center.on = function (eventName, callback) {
if (!center[eventName]) {
center[eventName] = [];
}
//保存回调函数
center[eventName].push(callback);
}
center.emit = function (eventName, params) {
//取出对应事件的回调函数
let callbackArr = center[eventName];
//一一调用每一个回调事件
callbackArr.map((callback) => {
callback(params);
})
}
center.off = function (eventName, callback) {
//情况1:只传eventName,移除所有事件
//情况2:传eventName和callback
if (!callback) {
center[eventName] = null;
}
else {
let callbackArr = center[eventName];
//删除指定的callback回调
let result = callbackArr.filter(callbackItem => {
if (callback == callbackItem) {
return false;
}
else {
return true;
}
})
//重新赋值
center[eventName] = result;
}
}
export default center;
原文地址:https://www.cnblogs.com/jusonhtml5/p/9339664.html
时间: 2024-10-08 08:42:50