Flutter EventBus

Flutter eventbus 官方文档 记录


class EventBus {
  // 私有构造器
  EventBus._internal();

  static EventBus _instance;

  static EventBus get instance => _getInstance();

  // 工厂模式
  factory EventBus() => _getInstance();

  // 构建单例
  static EventBus _getInstance() {
    if (null == _instance) {
      _instance = new EventBus._internal();
    }

    return _instance;
  }

  // 保存订阅者事件队列
  var _emap = new Map<Object, List<EventCallBack>>();

  // 添加订阅者

  void on(eventName, EventCallBack f) {
    if (eventName == null || f == null) {
      return;
    }

    _emap[eventName] ??= new List<EventCallBack>();

    _emap[eventName].add(f);
  }

  // 移除订阅者
  void off(eventName, [EventCallBack f]) {
    var list = _emap[eventName];

    if (eventName == null || list == null) {
      return;
    }

    if (f == null) {
      _emap[eventName] = null;
    } else {
      list.remove(f);
    }
  }

  // 发射事件 也有可能事件为空
  void emit(evenName, [arg]) {
    var list = _emap[evenName];

    if (list == null) {
      return;
    }

    // 开始通知订阅者
    var len = list.length - 1;
    for (int i = len; i > -1; --i) {
      list[i](arg);
    }
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容