发布订阅模式
let eventBus = (function () {
let pond = [];
const on = function on(type, func) {
!Array.isArray(pond[type]) ? pond[type] = [] : null;
let ary = pond[type];
if (ary.includes(func)) return;
ary.push(func);
}
const off = function off(type, func) {
if (!Array.isArray(pond[type])) throw new TypeError(`${type} 在自定义事件池中不存在!`);
let ary = pond[type],
i = 0,
len = ary.length,
item = null;
for (; i < len; i++) {
item = ary[i];
if (item === func) {
ary[i] = null;
break;
}
}
}
const emit = function emit(type, ...params) {
let ary = pond[type],
i = 0,
item = null;
if (!Array.isArray(pond[type])) throw new TypeError(`${type} 在自定义事件池中不存在!`);
for (; i < ary.length; i++) {
item = ary[i];
if (typeof item === 'function') {
item(...params);
continue;
}
ary.splice(i, 1);
i--;
}
}
return {
on,
off,
emit
}
})()
let fn1 = (param) => console.log(1, param);
let fn2 = (param) => console.log(2, param);
eventBus.on('A', fn1);
eventBus.on('A', fn2);
eventBus.on('B', fn1);
eventBus.on('B', fn2);
setTimeout(() => {
eventBus.emit('A', 'AAAAAA');
eventBus.emit('B', 'BBBBBB');
}, 2000);