Removing event listener which was added with bind

Asked
Active3 hr before
Viewed126 times

9 Answers

listenerevent
90%

In JavaScript, what is the best way to remove a function added as an event listener using bind()?,Although what @machineghost said was true, that events are added and removed the same way, the missing part of the equation was this:, This appears to be the correct approach when adding and removing event listeners from different classes or prototype functions, which is I believe the connection with this also applying to React components/classes. You're binding it at a common (e.g., root) instance level. – Keith DC Jan 21 '18 at 2:31 ,For those who have this problem while registering/removing listener of React component to/from Flux store, add the lines below to the constructor of your component:

So, to add or remove it, assign the reference to a variable:

var x = this.myListener.bind(this);
Toolbox.addListener(window, 'scroll', x);
Toolbox.removeListener(window, 'scroll', x);
load more v
88%

You put a click handler on an element using ‘addEventListener’, but now ‘removeEventListener’ won’t take it off. What’s going on?,‘Element’ is something like a button, ‘listenerType’ is what event you’re listening for (like a click), and ‘eventHandler’ is the work to do when that event happens.,Written use JavaScript’s classes and methods and using const so that ‘button’ can’t change later:,We can even provide bind with a second argument, which will be passed to the bound function.

If you got here from Google and don’t want to read this whole thing, here’s my example solution snippet. Copy/paste and fit to your code how you need:

const button = document.querySelector('.button') class MyClass {
   constructor(arg) {
      this.boundEventHandler = this.eventHandler.bind(this, arg) button.addEventListener('click', this.boundEventHandler)
   }
   eventHandler(arg) {
      console.log(arg)
   }
   removeListener() {
      button.removeEventListener('click', this.boundEventHandler)
   }
}
load more v
72%

var someEventHander = function() {
   console.log("do something");
}
var handlerCopy = someEventHandler.bind(var1, var2)
//add listener
document.getElementById("someid").addEventListener('click', handlerCopy, true);
//remove listener 
document.getElementById("someid").removeEventListener('click', handlerCopy, true);
65%

Given an event listener previously added by calling addEventListener(), you may eventually come to a point at which you need to remove it. Obviously, you need to specify the same type and listener parameters to removeEventListener(). But what about the options or useCapture parameters? ,removeEventListener(),Note that event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.,A string which specifies the type of event for which to remove an event listener.

target.removeEventListener(type, listener[, options]);
target.removeEventListener(type, listener[, useCapture]);
load more v
75%

Although what @machineghost said was true, that events are added and removed the same way, the missing part of the equation was this:,In JavaScript, what is the best way to remove a function added as an event listener using bind()?,A new function reference is created after .bind() is called.,The only way I can think of is to keep track of every listener added with bind.

(function() {

   // constructor
   MyClass = function() {
      this.myButton = document.getElementById("myButtonID");
      this.myButton.addEventListener("click", this.clickListener.bind(this));
   };

   MyClass.prototype.clickListener = function(event) {
      console.log(this); // must be MyClass
   };

   // public method
   MyClass.prototype.disableButton = function() {
      this.myButton.removeEventListener("click", ___________);
   };

})();
load more v
40%

Removing the listener works wonders, so I don't have to call .bind(this) to avoid -as you said- creating a new function reference. I ended up doing this on my component:,actually this did not remove the listener for me on an event for the document. I found that I had to set the function to a class variable first, then reference that variable to then remove,You can get this for free with arrow functions (https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56),I have two components and in both the components I am adding a hashChange listener and removing same way you told. But when first component is unmounted its hashChange event is still called and vice-versa. What's the problem? Is it a bug?

this._onResize = this._onResize.bind(this);
load more v
22%

Everything (eventname, function, and options) in the removeEventListener must match the one set when adding the event listener to the element.,using .bind on the function when adding an event listener will prevent the function from being removed, to actually remove the eventListener you can write:,The removeEventListener() method removes event handlers that have been attached with the addEventListener() method:,*It is not a best practice to attach functions to the Object prototype, hence you can remove the first line of this code and add a target to it as a first param.

The removeEventListener() method removes event handlers that have been attached with the addEventListener() method:

element.removeEventListener("mousemove", myFunction);
load more v
60%

Description: Remove a previously-attached event handler from the elements.,Event Handler Attachment ,Global Ajax Event Handlers ,To unbind just one previously bound handler, pass the function in as the second argument:

$("#foo").unbind();
load more v
48%

You can use the standard addEventListener and removeEventListener methods to add and remove event listeners imperatively.,Add and remove listeners imperativelyListener on the custom elementListener on child elementsListener on outside elements,To add event listeners to local DOM children, use on-event annotations in your template. This often eliminates the need to give an element an id solely for the purpose of binding an event listener.,To fire a custom event from the host element use the standard CustomEvent constructor and the dispatchEvent method.

Example:

<dom-module id="x-custom">
  <template>
    <button on-click="handleClick">Kick Me</button>
  </template>
  <script>
    class XCustom extends Polymer.Element {

      static get is() {return 'x-custom'}

      handleClick() {
        console.log('Ow!');
      }
    }
    customElements.define(XCustom.is, XCustom);
  </script>
</dom-module>
load more v

Other "listener-event" queries related to "Removing event listener which was added with bind"