Docs (4.0.0)
class ManagedObject method

listen

Adds a handler for all events emitted by this object.

listen(handler: (this: this, event: ManagedEvent) => Promise<void> | void): void

listen(): AsyncIterable<ManagedEvent>

Parameters

  • handler — A function (void return type, or asynchronous) that will be called for all events emitted by this object; the function is called with the this value set to the managed object, and a single event argument

Return value

If no callback function is provided, an async iterable that can be used instead

Description

This method adds a permanent listener for all events emitted by this object, in one of two ways. Either a callback function can be provided, or this method returns an async iterable that can be used to iterate over all events.

Callback function — If a callback function is provided, it will be called for every event that’s emitted by this object. The function is called with the this value set to the managed object, and a single event argument. The callback function can be asynchronous, in which case the result is awaited to catch any errors.

Async iterable — If no callback function is provided, this method returns an async iterable that can be used to iterate over all events using a for await...of loop. The loop body is run for each event, in the order they’re emitted, either awaiting new events or continuing execution immediately. The loop stops when the object is unlinked.

Note
This method adds a permanent listener. To prevent memory leaks, it may be better to use an Observer that can be stopped when needed, if the object is expected to outlive the listener.

Examples

// Handle all events using a callback function
someObject.listen((event) => {
  if (event.name === "Foo") {
    // ...handle Foo event
  }
});
// ... (code continues to run)
// Handle all events using an async iterable
for await (let event of someObject.listen()) {
  if (event.name === "Foo") {
    // ...handle Foo event
  }
}
// ... (code here runs after object is unlinked, or `break`)

Related

  • class ManagedObjectThe base class of all managed objects, which can be placed into a tree structure to enable event handling and data binding.