基于emitter封装的EventBus事件通知
基于 emitter 封装的 EventBus 事件通知
基于emitter封装的EventBus事件通知
基于 emitter 封装的 EventBus 事件通知
官网模块入口:
工具类
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
import { emitter } from '@kit.BasicServicesKit';
/// 事件通知工具类
export abstract class EventBus {
static send(
eventID: string,
eventData?: Object | Record<string, Object> | null,
) {
let data: string | undefined
if (eventData !== null && eventData !== undefined) {
if (typeof eventData === 'string') {
data = eventData
} else {
data = JSON.stringify(eventData)
}
}
emitter.emit(
eventID,
{
priority: emitter.EventPriority.HIGH
},
{
data: {
'data': data
}
},
);
}
static listen<T>(
eventID: string,
callback: (data?: T) => void,
) {
emitter.on(
eventID,
(eventData: emitter.EventData) => {
let data: string | undefined = eventData.data!['data']
if (data == undefined) {
callback(undefined)
} else {
if (data.startsWith("{") && data.endsWith("}")) {
callback(JSON.parse(data) as T)
} else {
callback(data as T)
}
}
},
);
}
static cancel(eventID: string) {
emitter.off(eventID);
}
}
使用
发送事件
**EventBus.send('name')**
监听事件
1
2
3
EventBus.listen<ImgInterface>('name', (e)=> {
console.log('click mine tab')
})
关闭事件
**EventBus.cancel('name')**
�
本文由作者按照 CC BY 4.0 进行授权