Hibok
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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