Files
auto-solution/modeler/src/utils/event.ts

79 lines
1.9 KiB
TypeScript
Raw Normal View History

/*
* This file is part of the kernelstudio package.
*
2026-03-27 10:35:23 +08:00
* (c) 2014-2026 zlin <admin@kernelstudio.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
export class EventError {
code: number;
status: number;
message: string | null;
stack: string | null;
constructor(code = 500, status = 500, message: string | null = null, stack: string | null = null) {
this.code = code;
this.status = status;
this.message = message;
this.stack = stack;
}
}
export class EventListener {
2026-03-27 10:35:23 +08:00
private _listeners: Record<string, Function[]>;
constructor(listeners: Record<string, Function[]> = {}) {
this._listeners = listeners;
}
all(): Record<string, Function[]> {
2026-03-27 10:35:23 +08:00
return { ...this._listeners }; // 返回副本,避免外部直接修改
}
has(name: string): boolean {
return Array.isArray(this._listeners[name]) && this._listeners[name].length > 0;
}
on(name: string, fn: Function): void {
if (!Array.isArray(this._listeners[name])) {
this._listeners[name] = [];
}
this._listeners[name].push(fn);
}
off(name: string): void {
delete this._listeners[name];
}
emit(name: string, options?: any): void {
const listeners = this._listeners[name];
if (Array.isArray(listeners)) {
// 复制一份避免在执行中修改数组导致问题
[...listeners].forEach(f => f(options));
}
}
2026-03-27 10:35:23 +08:00
clear(){
for (const key in this._listeners) {
if (this._listeners.hasOwnProperty(key)) {
delete this._listeners[key];
}
}
}
}
export const safePreventDefault = (event: any) => {
if (event && typeof event.preventDefault === 'function') {
event.preventDefault();
}
2026-03-27 10:35:23 +08:00
};
export const safeStopPropagation = (event: any) => {
if (event && typeof event.stopPropagation === 'function') {
event.stopPropagation();
}
2026-03-27 10:35:23 +08:00
};