Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"One-off" events are difficult because the mutable version of the events array is used during the emit phase #21

Open
arthur5005 opened this issue Jan 5, 2024 · 1 comment

Comments

@arthur5005
Copy link

arthur5005 commented Jan 5, 2024

Trying to make use of a "one-off" event with the braintree dropin.

The expectation is that this will work:

dropIn.on('changeActiveView', () => { console.log('usual changeActiveView handler'); });

//... later in the code

const emitOneOff = () => {
  console.log('foo');
  dropIn.off('changeActiveView', emitOneOff);
}
dropIn.on('changeActiveView', emitOneOff);

Problem is, the event array gets mutated in the when dropIn.off gets called during an emit phase, which shrinks the array, such that the usual event handler is ignored (dropped effectively) when the event is emitted.

This problem is usually dealt with (by many event-emitter libraries) by making a copy of the array during the emit phase, and iterating over an immutable version of that array to ensure all events are called.

Once implemented, a handy one or once function to handle the removal of the event after it being called is a nice to have, not required though.

@arthur5005
Copy link
Author

A simple change to the emit method:

Before

eventCallbacks.forEach(function (callback) {
  callback(eventPayload);
});

After

[...eventCallbacks].forEach(function (callback) {
  callback(eventPayload);
});

Would do the trick

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant