Skip to content

Commit

Permalink
Merge pull request #5 from busslina/busslina-branch
Browse files Browse the repository at this point in the history
Added listening any event functionality
  • Loading branch information
jumperchen authored Feb 14, 2022
2 parents 4eb1bbf + 018ef36 commit 1c4da1d
Showing 1 changed file with 33 additions and 0 deletions.
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

0 comments on commit 1c4da1d

Please sign in to comment.