Documentation

listen()

Adds a handler for all events emitted by this object.

listen(listener: ObservableObject.Listener<this>): this;

Parameters

Return value

The object itself

Description

This method adds a listener for all events emitted by this object. Either a callback function or an object with callback functions can be provided.

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 observable object, and a single event argument. The callback function can be asynchronous, in which case the result is awaited to catch any errors.

Callbacks object — If an object is provided, its functions (or methods) will be used to handle events. The handler function is called for all events, and the unlinked function is called when the object is unlinked. The init function is called immediately, with the object and a callback to remove the listener.

To be able to remove the event handler, use a callbacks object with an init function, and store the stop (second) argument in a variable. When needed, call the stop function to remove 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 a callbacks object
someObject.listen({
  init: (object, stop) => {
    // ... store `stop` in a variable if needed
  },
  handler: (object, event) => {
    // ...handle events here
  },
  unlinked: (object) => {
    // ...handle unlinking here
  },
});

Related