Hibok
您不能選擇超過 %s 個話題 話題必須以字母或數字為開頭,可包含連接號 ('-') 且最長為 35 個字
 
 
 
 
 
 

55 行
1.6 KiB

  1. //订阅者回调签名
  2. typedef void EventCallback(arg);
  3. class MessageMgr {
  4. static const String REFRESH_PUSH_PERMISSION ='refresh_push_permission';
  5. static const String RECEIVE_THIRD_SHARE ='receive_third_share';
  6. static const String TRANSLATE_HK_REFRESH_ORDER ='translate_hk_refresh_order';
  7. static const String TRANSLATE_HK_RECEIVE_ORDER ='translate_hk_receive_order';
  8. static const String TRANSLATE_HK_START_CHAT ='translate_hk_start_chat';
  9. //私有构造函数
  10. MessageMgr._internal();
  11. //保存单例
  12. static MessageMgr _singleton = new MessageMgr._internal();
  13. //工厂构造函数
  14. factory MessageMgr() => _singleton;
  15. //保存事件订阅者队列,key:事件名(id),value: 对应事件的订阅者队列
  16. var _emap = new Map<Object, List<EventCallback>>();
  17. //添加订阅者
  18. void on(eventName, EventCallback f) {
  19. if (eventName == null || f == null) return;
  20. _emap[eventName] ??= new List<EventCallback>();
  21. _emap[eventName].add(f);
  22. }
  23. //移除订阅者
  24. void off(eventName, [EventCallback f]) {
  25. var list = _emap[eventName];
  26. if (eventName == null || list == null) return;
  27. if (f == null) {
  28. _emap[eventName] = null;
  29. } else {
  30. list.remove(f);
  31. }
  32. }
  33. //触发事件,事件触发后该事件所有订阅者会被调用
  34. void emit(eventName, [arg]) {
  35. var list = _emap[eventName];
  36. if (list == null) return;
  37. int len = list.length - 1;
  38. //反向遍历,防止在订阅者在回调中移除自身带来的下标错位
  39. for (var i = len; i > -1; --i) {
  40. list[i](arg);
  41. }
  42. }
  43. }