Skip to content

Bug: Event listener memory leak in editable_controller.js #33

Closed

Description

@philipithomas

Description

In app/javascript/controllers/editable_controller.js:16-28, connect() adds an anonymous function as an event listener, and disconnect() creates a new anonymous function for removeEventListener. Since the function references are different, the original listener is never removed.

connect() {
  this.contentTarget.addEventListener("keypress", (e) => {
    if (e.which === 13) { e.preventDefault(); }
  });
}

disconnect() {
  this.contentTarget.removeEventListener("keypress", (e) => {
    if (e.which === 13) { e.preventDefault(); }
  });
}

Recommendation

Store the handler as a class property:

connect() {
  this.keyPressHandler = (e) => { if (e.which === 13) e.preventDefault(); };
  this.contentTarget.addEventListener("keypress", this.keyPressHandler);
}

disconnect() {
  this.contentTarget.removeEventListener("keypress", this.keyPressHandler);
}

Severity

Medium

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions