UNPKG

typescript-util

Version:

JS/TS 的简单工具

81 lines 2.46 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SimpleEventCenter = void 0; const ArrayTool_1 = require("../../tool/ArrayTool"); const ObjectTool_1 = require("../../tool/ObjectTool"); // noinspection JSUnusedGlobalSymbols /** * SimpleEventCenter * @author LL * @date 2022/1/27 18:00 */ 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_1.ArrayTool.isEmpty(consumers)) { return; } let notNullConsumers = consumers.filter(i => ObjectTool_1.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_1.ArrayTool.isEmpty(list)) { return; } list[id] = null; } addListener(name, callback, container) { const list = container[name]; if (ArrayTool_1.ArrayTool.isEmpty(list)) { // @ts-ignore container[name] = [callback]; return 0; } // @ts-ignore return list.push(callback); } } exports.SimpleEventCenter = SimpleEventCenter; //# sourceMappingURL=SimpleEventCenter.js.map