From 018ef36d2ec35449ccd536af3cb0c54f04fad2b1 Mon Sep 17 00:00:00 2001 From: Vicente Date: Fri, 11 Feb 2022 07:43:46 +0100 Subject: [PATCH] Added listening any event functionality --- lib/src/util/event_emitter.dart | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/lib/src/util/event_emitter.dart b/lib/src/util/event_emitter.dart index 2916c70..06f9e10 100644 --- a/lib/src/util/event_emitter.dart +++ b/lib/src/util/event_emitter.dart @@ -17,6 +17,11 @@ import 'dart:collection' show HashMap; */ typedef dynamic EventHandler(T data); +/** + * Handler type for handling the event emitted by an [AnyEventHandler]. + */ +typedef dynamic AnyEventHandler(String event, T data); + /** * Generic event emitting and handling. */ @@ -33,6 +38,11 @@ class EventEmitter { Map> _eventsOnce = new HashMap>(); + /** + * List of handlers that listen every event + */ + List _eventsAny = []; + /** * Constructor */ @@ -54,6 +64,10 @@ class EventEmitter { this._eventsOnce.remove(event)?.forEach((EventHandler handler) { handler(data); }); + + this._eventsAny.forEach((AnyEventHandler handler) { + handler(event, data); + }); } /** @@ -74,6 +88,13 @@ class EventEmitter { this._eventsOnce[event]!.add(handler); } + /** + * This function binds the [handler] as a listener to any event + */ + void onAny(AnyEventHandler handler) { + this._eventsAny.add(handler); + } + /** * This function attempts to unbind the [handler] from the [event] */ @@ -93,12 +114,24 @@ class EventEmitter { } } + /** + * This function attempts to unbind the [handler]. + */ + void offAny([AnyEventHandler? handler]) { + if (handler != null) { + this._eventsAny.remove(handler); + } else { + this._eventsAny.clear(); + } + } + /** * This function unbinds all the handlers for all the events. */ void clearListeners() { this._events = new HashMap>(); this._eventsOnce = new HashMap>(); + this._eventsAny.clear(); } /**