Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.off() is not removing binding

For some reason jQuery.off('click') doesn't seem to be working here. When the 'Yes' button is clicked in the model another model just pops up. What am I doing wrong?

code:

$(function(){

  //If there are warnings on the page bind alert
  if ($('.renewal-warning').length > 0){

    (function (){

      $('#signRentalContainer').on('click', '.renewal-warning', function(e){

        var buttonHandle = this;

        //Prevent submission
        e.preventDefault();

        //Show warning model
        $.modal({
          content: $('#renewalWarning').html(),
          title: "Order Renewal Warning",
          buttons: {
            'Yes': function(win) { $(buttonHandle).off('click').click(); },
            'No': function(win) { win.closeModal(); }
          },
          maxWidth: 250,
          closeButton: false
        });
      });
    })();
  }
});
like image 977
Steven Avatar asked Jan 15 '12 07:01

Steven


People also ask

Does jQuery remove unbind events?

jQuery unbind() MethodThe unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs.

How do you turn off a function in jQuery?

jQuery off() MethodThe off() method is most often used to remove event handlers attached with the on() method. As of jQuery version 1.7, the off() method is the new replacement for the unbind(), die() and undelegate() methods.

How do you unbind an event?

Select the selector on which the event handler is to be removed. Use the unbind() method to remove event. After click on the function under which unbind works will remove the event handler.

What is bind and unbind in jQuery?

jQuery bind() function is used to attach an event handler to elements, while the unbind() is used to detached an existing event handler from elements.


2 Answers

Because the this refer to the context of the handle function, not the function itself.

Try making it a named function, then refer to it when you call off:

$("body").off("click", '#signRentalContainer', buttonHandle);

BTW, any reason we can't use unbind directly here?

$("#signRentalContainer").unbind("click");

like image 89
satoru Avatar answered Oct 18 '22 16:10

satoru


Pretty sure you're going to need to provide it the same element, as well as the same selector.

$('#signRentalContainer').off('click', '.renewal-warning');

In the .on() handler, this is the '.renewal-warning' element that was clicked, not the #signRentalContainer element.


If there are several of these '.renewal-warning' elements, and you only want to disable one at a time, the simplest way is to change its class so that it no longer matches the selector.

$(this).removeClass('renewal-warning')
       .addClass('renewal-warning-disabled');
like image 10
user1106925 Avatar answered Oct 18 '22 16:10

user1106925