Skip to content Skip to sidebar Skip to footer

Removing Event Listner In Javascript

I created a class in JavaScript which does specific task related key call (key press ) when class is initiated. Class have a function 'receaveKey' which is referenced by addEventLi

Solution 1:

You have to remove the same function you added, but bind always returns a new function.

So you'll have to remember the first one, then use it when removing:

this.boundReceaveKey = this.receaveKey.bind(this);
document.addEventListener("keypress",this.boundReceaveKey);

// ...later...
document.removeEventListener("keypress",this.boundReceaveKey);
this.boundReceaveKey = undefined; // If you don't need it anymore

Side note: The spelling is "receive."


Your requested example:

functionThingy(name) {
  this.name = name;
  this.element = document.getElementById("the-button");
  this.bindEvents();
}
Thingy.prototype.bindEvents = function() {
  if (!this.boundReceiveClick) {
    this.boundReceiveClick = this.receiveClick.bind(this);
    this.element.addEventListener("click", this.boundReceiveClick, false);
  }
};
Thingy.prototype.unbindEvents = function() {
  if (this.boundReceiveClick) {
    this.element.removeEventListener("click", this.boundReceiveClick, false);
    this.boundReceiveClick = undefined;
  }
};
Thingy.prototype.receiveClick = function() {
  var p = document.createElement("p");
  p.innerHTML = "Click received, name = " + this.name;
  document.body.appendChild(p);
};

var t = newThingy("thingy");
t.bindEvents();

document.getElementById("the-checkbox").addEventListener("click", function() {
  if (this.checked) {
    t.bindEvents();
  } else {
    t.unbindEvents();
  }
}, false);
<inputid="the-button"type="button"value="Click me"><br><label><inputid="the-checkbox"type="checkbox"checked> Bound, when this is unchecked the button won't do anything</label>

Solution 2:

.bind returns a new function with its context bound.

You'll need to pass it a function reference to be able to then remove it as a acallback.

var boundFn = this.receiveKey.bind( this )
element.addEventListener( 'keypress', boundFn )
element.removeEventListener( 'keypress', boundFn )

Solution 3:

.bind creates a new function.

You could do

this.receaveKey = function() {}.bind(this)

Post a Comment for "Removing Event Listner In Javascript"