use static method

void use(
  1. Listenable listener,
  2. void action()
)

The use method takes as an argument a function to be used as a listener and adds it to the Listenable listeners.

Also removes the listener when the component is disposed.

Implementation

static void use(Listenable listener, void Function() action) {
  return VComponent.run((vComponent) {
    final context = VContext(context: vComponent.context, key: _key);
    final Set<Listenable> listeners = context.init('listeners', () => {});
    if (!listeners.contains(listener)) {
      // ignore: prefer_function_declarations_over_variables
      final h = () {
        try {
          action();
        } catch (e, s) {
          throw WrappedException(
              "An error occurred while executing the listener action on ${listener.runtimeType})' for component '$vComponent'",
              e,
              s);
        }
      };
      listeners.add(listener);
      listener.addListener(h);
      vComponent.addDisposeHandler(vComponent, () {
        listener.removeListener(h);
      });
    }
  });
}