event.dart 573 B

1234567891011121314151617181920212223
  1. class Event {
  2. final Map<String, List<Function>> _events = {};
  3. Event on(String key, Function handle) {
  4. final handles = _events[key] ??= [];
  5. if (!handles.contains(handle)) handles.add(handle);
  6. return this;
  7. }
  8. Event emit(String key, dynamic arg) {
  9. final handles = _events[key];
  10. handles?.forEach((it) => it(arg));
  11. return this;
  12. }
  13. Event off(String key, Function handle) {
  14. final handles = _events[key];
  15. if (handles == null) return this;
  16. handles.remove(handle);
  17. if (handles.isEmpty) _events.remove(key);
  18. return this;
  19. }
  20. }