Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added listening any event functionality #5

Merged
merged 1 commit into from
Feb 14, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions lib/src/util/event_emitter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ import 'dart:collection' show HashMap;
*/
typedef dynamic EventHandler<T>(T data);

/**
* Handler type for handling the event emitted by an [AnyEventHandler].
*/
typedef dynamic AnyEventHandler<T>(String event, T data);

/**
* Generic event emitting and handling.
*/
Expand All @@ -33,6 +38,11 @@ class EventEmitter {
Map<String, List<EventHandler>> _eventsOnce =
new HashMap<String, List<EventHandler>>();

/**
* List of handlers that listen every event
*/
List<AnyEventHandler> _eventsAny = [];

/**
* Constructor
*/
Expand All @@ -54,6 +64,10 @@ class EventEmitter {
this._eventsOnce.remove(event)?.forEach((EventHandler handler) {
handler(data);
});

this._eventsAny.forEach((AnyEventHandler handler) {
handler(event, data);
});
}

/**
Expand All @@ -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]
*/
Expand All @@ -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<String, List<EventHandler>>();
this._eventsOnce = new HashMap<String, List<EventHandler>>();
this._eventsAny.clear();
}

/**
Expand Down