0

I am trying to unbind an event handler that has been added to an object's prototype. The (cut-down) code in question is:

MyClass.prototype.bindEvents = function() {
  var thisObj = this;
  this.$tabs.on("click", function(e) {
    return thisObj.handleTabClick($(this), e);
  });
}

MyClass.prototype.unbindEvents = function() {
  this.$tabs.off("click", this.handleTabClick);
}

MyClass.prototype.handleTabClick = function($tab, e) {
  // do something
}

I know that I can (and did) complete clear the click event by doing

this.$tabs.off("click");

but there is another event handler on there which I wish to keep.

How do I unbind a single event within the prototype structure?

  • 1
    http://stackoverflow.com/questions/5136296/is-it-possible-to-remove-one-specific-event-handler-from-an-event-with-multiple May be of help – Sandeep Nayak Oct 13 '15 at 12:13

1 Answers1

0

You can add a namespace to the event when you create it which you can then specifically reference when you remove the event handler. try this:

MyClass.prototype.bindEvents = function() {
    var thisObj = this;
    this.$tabs.on("click.foo", function(e) {
        return thisObj.handleTabClick($(this), e);
    });
}

MyClass.prototype.unbindEvents = function() {
    this.$tabs.off("click.foo");
}

For more information see the 'Event names and namespaces' section of http://api.jquery.com/on/

Also note that your method of passing the click handler through an anonymous function to the handleTabClick function is redundant, you can simply do this:

this.$tabs.on("click.foo", thisObj.handleTabClick);

MyClass.prototype.handleTabClick = function(e) {
    var $tab = $(this); 
    // do something
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339