Correctly remove anonymous function event handlers


I'm trying to figure out how best to remove anonymous event handlers using jQuery.

I define a variable to hold my jQuery object:

 var dom = $('#private-module');

Later on in my object:

  run: function () {
    var button, that = this; 

    button = dom.append('<button class="btn">Click Me</button>');
    button.on('click', function(event) {
      console.log('Clicked!');
      that.destroy();
    });
  },

  destroy: function () {
    var button; 

    button = dom.find('.btn');
    button.off('click');  
  }

No matter what I do, I cannot kill the click handler on the button. Feels like my understanding here of scope is flawed. What is the preferred way, in this situation to remove the handler? I've tried namespacing the events and all sorts but no luck so I am guessing it's something simple that I've overlooked. Perhaps I shouldn't even be using anonymous functions for event handlers.

Just to bolt something on to my reasoning for using .append:

http://jsperf.com/jquery-append-vs-appendto

Here is the final solution:

dom.append('<button class="btn">Send Message</button>');
button = dom.find('.btn');
button.on('click', function (event) {
   sendTestMessage();
   that.destroy();
});

I also agree and understand about using the .one method. Thanks for that.

button = dom.append('<button class="btn">Click Me</button>');

returns the dom, not the button, so you bound the event handler on the dom.

Change to:

button = $('<button class="btn">Click Me</button>').appendTo(dom);

And here is the working demo.


the problem is that button is dom and not .btn:

button = dom.append('<button class="btn">Click Me</button>');

//a console.log(button) here reveals that button is "dom"

//and thus you are adding a handler to "dom
button.on('click', function(event) {
    console.log('Clicked!');
    that.destroy();
});

one way to do this thanks to the delegation powers of .on() is to add the child selector of the element you want to bind the handler as second parameter.

button.on('click', '.btn'  function(event) {
    //the value of "this" in here is the ".btn"
    console.log('Clicked!');
    that.destroy();
});

in destroy, we use .off() with a second parameter pertaining to .btn:

button.off('click', '.btn');