Correctly remove anonymous function event handlers

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

I define a variable to store the jQuery object:

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

Later 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 that my understanding of scale here is erroneous. What is the preferred way to remove the handler in this situation? I tried namespacing events and all kinds, but no luck, so I guess it's just that I forgot. Perhaps I should not even use anonymous functions for event handlers.

Just to say something about 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();
});

.one. .

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

dom, , dom.

:

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

.

+7

, button dom, .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();
});

.on() - , .

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

destroy, .off() , .btn:

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

All Articles