1

I am using jQuery 1.10.2, but would also like to know the solution for the most modern version if it is not the same.

I have a JavaScript file that will add and remove some custom events.

$(window).on('clicked_button', function(event) {
    // Do stuff
});

if (someCriteria) {
    $(window).off('clicked_button');
}

if (otherCriteria) {
    $(window).trigger('clicked_button');
}

I know that you can loop through the events in the data object to check if the event is already bound or not, but is that necessary? I don't care if the event is already bound or not, I just want to make sure it won't be bound after someCriteria is met.

When I run $(window).off('clicked_button'); in the js console on Firefox, it just returns the window object. Can I assume then that the off() function will not throw an error if the event isn't already bound? I'd prefer to just use off() and let it silently fail, than having to loop through the bound events before unbinding it.

I would need this to work for the modern browsers and IE 9+.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Katrina
  • 1,922
  • 2
  • 24
  • 42

1 Answers1

2

According to the jQuery API documentation, off() was added in version 1.7. $(window).off('clicked_button') will fail silently even if the custom 'clicked_button' event was never bound to an element.

Similarly, calling $(window).off() will remove all event handlers without error, even if none have been bound.

Ryan Dantzler
  • 1,124
  • 1
  • 8
  • 18
  • Thank you. I couldn't find in the docs where it explicitly said that it would throw an error or not. – Katrina Apr 01 '16 at 17:02