Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 410
backdesk Avatar asked Mar 14 '12 10:03

backdesk


1 Answers

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.

like image 70
xdazz Avatar answered Sep 20 '22 17:09

xdazz