Sobes.tech
Middle+

What happens when you resubscribe to the same handler? How does the order of calls change?

sobes.tech AI

Answer from AI

When subscribing again to the same handler (for example, in an event system or on DOM events in JavaScript), it usually results in adding this handler to the list of listeners once more. This means that when the event occurs, the handler will be called as many times as it was subscribed.

The order of invocation remains the same: handlers are called in the order they were added. If the same handler is added multiple times, it will be called multiple times in succession at the points where it was added.

Example in JavaScript:

const button = document.querySelector('button');
function handler() {
  console.log('Clicked');
}

button.addEventListener('click', handler);
button.addEventListener('click', handler);

// When clicking, the console will output:
// Clicked
// Clicked

To avoid duplicate subscriptions, it is common to check whether the handler is already subscribed before adding it, or to use methods that do not add duplicates (such as once) or remove the handler before re-adding it.

What happens when you resubscribe to the same… - sobes.tech