emitter工具函数
emitter工具函数class
/**
* @Author:
* @Date: 2025.11.19
* @Description: emitter环境与函数
*/
import { emitter } from '@kit.BasicServicesKit';
export class EmitterUtil {
/**
* 发送事件
* @param eventId 事件标识(支持字符串/数字类型)
* @param eventData 发送的数据内容
* @param priority 事件优先级(默认HIGH)
*/
static post<T>(
eventId: string | number,
eventData: T,
priority: emitter.EventPriority = emitter.EventPriority.HIGH
) {
if (!eventId || (typeof eventId === 'string' && !eventId.trim())) {
throw new Error('事件ID不能为空');
}
const options: emitter.Options = { priority };
emitter.emit(eventId.toString(), options, { data: eventData });
}
/**
* 发送事件
* @param eventId 事件标识(支持字符串/数字类型)
* @param eventData 发送的数据内容
* @param priority 事件优先级(默认HIGH)
*/
static postWithoutData(
eventId: string | number,
priority: emitter.EventPriority = emitter.EventPriority.HIGH
) {
if (!eventId || (typeof eventId === 'string' && !eventId.trim())) {
throw new Error('事件ID不能为空');
}
const options: emitter.Options = { priority };
emitter.emit(eventId.toString(), options);
}
/**
* 订阅事件
* @param eventId 事件标识
* @param callback 回调处理函数
*/
static on<T>(eventId: string | number, callback: (data?: T) => void) {
emitter.on(eventId.toString(), (eventData: emitter.GenericEventData<T>) => {
if (eventData.data !== undefined){
console.warn(`事件${eventId}接收到空数据`);
}
callback(eventData.data);
});
}
/**
* 订阅事件一次
* @param eventId 事件标识
* @param callback 回调处理函数
*/
static onOnce<T>(eventId: string | number, callback: (data?: T) => void) {
emitter.once(eventId.toString(), (eventData: emitter.GenericEventData<T>) => {
if (eventData.data !== undefined){
console.warn(`事件${eventId}接收到空数据`);
}
callback(eventData.data);
});
}
/**
* 单次订阅事件
* @param eventId 事件标识
* @param callback 回调处理函数
*/
static once<T>(eventId: string | number, callback: (data?: T) => void) {
emitter.once(eventId.toString(), (eventData: emitter.GenericEventData<T>) => {
if (eventData.data !== undefined){
console.warn(`事件${eventId}接收到空数据`);
}
callback(eventData.data);
});
}
/**
* 取消事件订阅
* @param eventId 事件标识
*/
static off(eventId: string | number) {
emitter.off(eventId.toString());
}
/**
* 获取事件订阅数
* @param eventId 事件标识
*/
static getListenerCount(eventId: string | number): number {
return emitter.getListenerCount(eventId.toString());
}
}
浙公网安备 33010602011771号