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

Calling event listener remover function on EventsOnce after it has fired causes TypeError #3850

Open
dreamscached opened this issue Oct 22, 2024 · 1 comment

Comments

@dreamscached
Copy link

dreamscached commented Oct 22, 2024

Wails 2.9.1

Title basically explains the issue, which occurs here:

function listenerOff(listener) {
const eventName = listener.eventName;
// Remove local listener
eventListeners[eventName] = eventListeners[eventName].filter(l => l !== listener);
// Clean up if there are no event listeners left
if (eventListeners[eventName].length === 0) {
removeListener(eventName);
}
}

This happens whenever a one-time event handler (registered with EventsOnce) is removed by remover function (namely, from frontend code) after it has already fired (and therefore its listener is now removed.)

Consider the following example:

// Code in JS frontend

const eventRemover = EventsOnce("myEvent", () => console.log("Event fired.");
window.removeEvent = () => eventRemover();
window.emitEvent = () => EventsEmit("emitMyEvent");
// Code in Go backend

func (a *App) onStartup() {
    runtime.EventsOn(a.Context, "emitMyEvent", func(optionalData ...interface{}) {
        runtime.EventsEmit(a.Context, "myEvent")
    })
}

Now, when myEvent fires and removes itself, its remover function will now cause a TypeError:
demo

This does not happen when the remover is called before event is fired:
demo

This can be fixed pretty easily, by making a remover no-op if the listener can't be found:

 function listenerOff(listener) {
   const eventName = listener.eventName;
+  const listeners = eventListeners[eventName];
+  if (listeners === undefined) return;
  
   eventListeners[eventName] = eventListeners[eventName].filter((l) => l !== listener);
   if (eventListeners[eventName].length === 0) {
       removeListener(eventName);
   }
 }
@leaanthony
Copy link
Member

Good catch. Feel free to open a PR 👍

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

2 participants