typescript-util
Version:
JS/TS 的简单工具
77 lines • 2.25 kB
JavaScript
import { ArrayTool } from '../../tool/ArrayTool';
import { ObjectTool } from '../../tool/ObjectTool';
// noinspection JSUnusedGlobalSymbols
/**
* SimpleEventCenter
* @author LL
* @date 2022/1/27 18:00
*/
export class SimpleEventCenter {
container = {};
tempContainer = {};
push(event) {
this.dispatch(event, this.container, false);
this.dispatch(event, this.tempContainer, true);
}
removeEventListener(name, id) {
this.remove(name, id, this.container);
this.remove(name, id, this.tempContainer);
}
addEventListener(name, callback) {
return this.addListener(name, callback, this.container);
}
addOnceEventListener(name, callback) {
return this.addListener(name, callback, this.tempContainer);
}
/**
* @param event 发生的事件
* @param {Record<keyof R, Array<Consumer<Event>>>} container 事件监听器容器
* @param {boolean} isOnce 仅仅调用一次
*/
dispatch(event, container, isOnce) {
let name = event.getName();
// @ts-ignore
const consumers = container[name];
if (ArrayTool.isEmpty(consumers)) {
return;
}
let notNullConsumers = consumers.filter(i => ObjectTool.isNotNull(i));
for (const consumer of notNullConsumers) {
try {
consumer?.(event);
}
catch (e) {
console.debug('事件回调错误: ', e);
}
}
if (isOnce) {
// @ts-ignore
delete consumers[name];
}
}
/**
*
* @param {K} name
* @param id
* @param {Record<keyof R, Array<Consumer<Event> | null>>} container
* @private
*/
remove(name, id, container) {
const list = container[name];
if (ArrayTool.isEmpty(list)) {
return;
}
list[id] = null;
}
addListener(name, callback, container) {
const list = container[name];
if (ArrayTool.isEmpty(list)) {
// @ts-ignore
container[name] = [callback];
return 0;
}
// @ts-ignore
return list.push(callback);
}
}
//# sourceMappingURL=SimpleEventCenter.js.map