Open a preview, close it, and open it again. The next update produces two callback calls. Reloading the application makes the problem disappear until you repeat that sequence. Before changing the event producer, look at what the first preview left behind.

Suppose a shared event bus outlives each preview. A small Node.js example can model these openings and closings without rendering a window. The useful question is which subscriptions survive each step.

Count subscriptions across one reopen

Start with one emission of change after reopening. Record both the number of listeners and the identity of the view that receives the update:

Step Broken listener count Fixed listener count
Before opening 0 0
Open the first view 1 1
Close the first view 1 0
Open the second view 2 1
Emit once First and second views called Second view called

The first suspicious transition is closing the first view. Its subscription should disappear there. Reading only the update handler misses that earlier mistake.

In the example, listenerCount('change') supplies the count and emit triggers the callbacks synchronously. No timer or repeated click is needed to reproduce the duplicate delivery.

Follow the callback object, not its text

Here is the broken mount function. It returns a function that the caller should invoke when the view closes:

export function mountUnsafeView(bus, publish) {
  bus.on('change', (value) => publish(value));
  return () => bus.off('change', (value) => publish(value));
}

The arrow function passed to on and the arrow function passed to off look identical, but evaluating each expression creates a separate function object. Cleanup searches for the new object; the original subscription stays registered. The first callback also keeps access to its original publisher.

Node documents off as an alias of removeListener, which removes a specified listener. Its Events API reference is the rule to check here. In this EventEmitter example, matching the event name and callback body is insufficient: cleanup needs the registered function reference.

Let each mount return its own cleanup

Save the callback once and close over that same reference:

export function mountView(bus, publish) {
  const onChange = (value) => publish(value);
  bus.on('change', onChange);
  let disposed = false;
  return function dispose() {
    if (disposed) return;
    disposed = true;
    bus.off('change', onChange);
  };
}

Every mount creates its own onChange. The returned dispose removes that mount’s subscription and does nothing on later calls. The flag makes repeated cleanup explicit; the separate callback reference keeps one mount distinct from another.

Even if two views receive the same publish function, their subscriptions remain separate because each mount creates its own wrapper. Passing publish straight to on from both views would register the same function twice; one off would then remove only one copy, as the last reproduction shows. Keep the returned cleanup with the view that created it. If it is discarded or overwritten before closing, the corrected function cannot remove itself.

Test cleanup while another subscriber is listening

A test that expects zero listeners after closing an otherwise empty view is useful, but too narrow. A tempting replacement using removeAllListeners would pass it while silencing every other consumer of the shared bus.

The example therefore registers an independent observer, opens an old view, closes it, opens a new view, and calls the old cleanup again. It then emits an update and checks the recipients:

Observation Required result
Update after repeated old cleanup Observer and new view receive it
Update after closing the new view twice Only observer receives it
Two views share one publisher; close one The remaining view still receives updates
Three open/close cycles One call per open; none after closing

These assertions check deliveries as well as counts. A count of one alone cannot tell whether the surviving listener belongs to the observer or to the wrong view. Repeating dispose after a newer mount specifically catches cleanup that reaches into shared mutable state.

Read the real caller through the exit path

Use the same order when reading unfamiliar code:

  1. Find the event bus creation. Determine whether it survives navigation or belongs to one view.
  2. Find each subscription site and count how often opening, rendering, or reconnecting can reach it.
  3. Track the exact callback reference from registration to removal.
  4. Find the caller of mountView and where it stores the returned function.
  5. Follow every relevant exit to the call to dispose, including replacement and failed setup paths.

Beside each registration, note which object stores the subscription and when it releases it. A cleanup function that exists but is never called needs a different fix from one called with the wrong reference. If callbacks start asynchronous work, continue into that work too; removing a subscription does not undo an operation already started. Tracing asynchronous UI state covers that next step.

Run the example and check its limits

Download event-listener-lifecycle.mjs and run it with Node.js 22 or later:

node --test event-listener-lifecycle.mjs

All five tests pass. Two named reproduce: deliberately assert broken outcomes: a leaked subscription after reopening, and a callback registered twice surviving one removal. The other three check cleanup, repeated calls, and independent subscribers. No dependencies or timers are required.

This lab models view lifetimes with EventEmitter; it does not model a browser or promise identical behavior from DOM EventTarget. It registers once per mount and removes between emissions. Removal during an active emission, framework effects, and cancellation of ongoing work need their own checks against the API actually used.

For a practical starting point in Yenpo, keep the entry and cleanup files open while reading and follow the stored callback through both.