• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

wkin

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

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());
  }
}

posted on 2026-01-16 10:38  带头大哥d小弟  阅读(3)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3