forked from alibaba/lowcode-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevent.ts
More file actions
88 lines (77 loc) · 2.55 KB
/
event.ts
File metadata and controls
88 lines (77 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { IEditor, IEventBus } from '@alilc/lowcode-editor-core';
import { getLogger, isPluginEventName } from '@alilc/lowcode-utils';
import { IPublicApiEvent, IPublicTypeDisposable } from '@alilc/lowcode-types';
const logger = getLogger({ level: 'warn', bizName: 'shell-event' });
type EventOptions = {
prefix: string;
};
const eventBusSymbol = Symbol('eventBus');
export class Event implements IPublicApiEvent {
private readonly [eventBusSymbol]: IEventBus;
private readonly options: EventOptions;
constructor(eventBus: IEventBus, options: EventOptions, public workspaceMode = false) {
this[eventBusSymbol] = eventBus;
this.options = options;
if (!this.options.prefix) {
logger.warn('prefix is required while initializing Event');
}
}
/**
* 监听事件
* @param event 事件名称
* @param listener 事件回调
*/
on(event: string, listener: (...args: any[]) => void): IPublicTypeDisposable {
if (isPluginEventName(event)) {
return this[eventBusSymbol].on(event, listener);
} else {
logger.warn(`fail to monitor on event ${event}, event should have a prefix like 'somePrefix:eventName'`);
return () => {};
}
}
/**
* 监听事件,会在其他回调函数之前执行
* @param event 事件名称
* @param listener 事件回调
*/
prependListener(event: string, listener: (...args: any[]) => void): IPublicTypeDisposable {
if (isPluginEventName(event)) {
return this[eventBusSymbol].prependListener(event, listener);
} else {
logger.warn(`fail to prependListener event ${event}, event should have a prefix like 'somePrefix:eventName'`);
return () => {};
}
}
/**
* 取消监听事件
* @param event 事件名称
* @param listener 事件回调
*/
off(event: string, listener: (...args: any[]) => void) {
this[eventBusSymbol].off(event, listener);
}
/**
* 触发事件
* @param event 事件名称
* @param args 事件参数
* @returns
*/
emit(event: string, ...args: any[]) {
if (!this.options.prefix) {
logger.warn('Event#emit has been forbidden while prefix is not specified');
return;
}
this[eventBusSymbol].emit(`${this.options.prefix}:${event}`, ...args);
}
/**
* DO NOT USE if u fully understand what this method does.
* @param event
* @param args
*/
__internalEmit__(event: string, ...args: unknown[]) {
this[eventBusSymbol].emit(event, ...args);
}
}
export function getEvent(editor: IEditor, options: any = { prefix: 'common' }) {
return new Event(editor.eventBus, options);
}