12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- typedef void EventCallback(dynamic arg);
- var bus = EventBus();
- class EventBus {
- EventBus._internal();
-
- static final EventBus _singleton = EventBus._internal();
-
- factory EventBus() => _singleton;
- final _subscriptions = <String, List<Subscription>>{};
-
- Subscription on(String eventName, EventCallback callback) {
- final sub = Subscription(eventName: eventName, callback: callback);
- _subscriptions.putIfAbsent(eventName, () => []).add(sub);
- return sub;
- }
-
- void off(String eventName, [Subscription? subscription]) {
- if (_subscriptions.containsKey(eventName)) {
- if (subscription == null) {
- _subscriptions[eventName]!.clear();
- } else {
- _subscriptions[eventName]!.removeWhere((sub) => sub.callback == subscription.callback);
- }
- }
- }
-
- void offAll() {
- _subscriptions.clear();
- }
-
- void emit(String eventName, [arg]) {
- for (final sub in _subscriptions[eventName] ?? []) {
- sub.callback(arg);
- }
- }
- }
- class Subscription {
- final String eventName;
- final EventCallback callback;
- Subscription({required this.eventName, required this.callback});
- }
|