on<T> method

EventListener<T> on<T>(
  1. String? type,
  2. EventCallback<T> callback
)

Attach a listener to an emitter. Calls the callback whenever there's a new event of the specified event type and data type.

If the emitted event doesn't match the specified type and data type, the callback will not be called. This method can be used with generalized types, such as Object/dynamic and other super classes.

A EventListener is returned, which has all information about the listener and can be used to cancel the subscription.

  EventEmitter events = EventEmitter();
    ...
  events.on('message', (String data) => print('String: $data'));
  events.on('message', (Event<String> event) => print('String event: ${event.data}'));

  // [Output]
  // String: Hello World
  // String event: Hello World

When using the callback, it's possible to handle the event data, as well as the event itself. Do this by using the types Event<T> and T in the callback.

Implementation

EventListener<T> on<T>(String? type, EventCallback<T> callback) {
  final listener = EventListener<T>(type, callback);
  addEventListener(listener);
  return listener;
}