jQuery allows you to define extra functionality around events, namely it is possible to define behavior that happens when the first event handler is registered (setup), each time a new event handler is added (add), removed (remove) and when the last event handler is removed (teardown).
This is how, for example, you take advantage of the special event’s api for the click event:
jQuery.event.special.click = {
setup: function(data, namespaces, handler) { },
add: function(handlerObj) { },
remove: function(handlerObj) { },
teardown: function(namespaces) { },
_default: function (event) { }
};
If you are wondering how the special events api is normally used, think of this scenario: you want all elements that have a click event handler registered in them to show a “hand” when the mouse hovers over them (this might be useful if you want to make a div clickable, which usually does not display any visual cues that let the user know that the div can be clicked). You also want this effect to go away as soon as the last event handler is unregistered.
You can achieve this without using the special events api by setting the cursor property when you register and unregister the click event:
$('#myElement').css("cursor", "pointer");
$('#myElement').on("click", function(){
//...
};
The resetting of the cursor is more complicated, you’d have to keep track of the event handlers and remove it when you remove the last handler.
With special events it’s simple:
jQuery.event.special.click = {
setup: function(){
$(this).css("cursor", "pointer");
return false; //this is important because click is a native event. It instructs
//jQuery to use native DOM methods to register and unregister
//the event (for custom events you don't need to return anything)
};
teardown: function(){
$(this).css("cursor", "");
return false; //same as above
};
};
Try it here
If you want to really understand the special events api, and really understand the example I suggest you read this
What does all this have to do with the title of this post? You can add debugger statements in any of the special event’s api methods, namely on add and remove so that you can find out (looking at the stack trace in chrome’s developer tools) where an event handler was registered and/or unregistered. This might be useful in large codebases that you are not familiar with, especially when someone decides to do something like $(someSelector).off()
(which will deregister all events) and you are left wondering why your custom event isn’t firing.
The way to do it is to include the following snippet at the head of the page (after you include jQuery) you are analysing:
<head>
<!-- after including jQuery -->
<script>
$.event.special.YourCustomEvent = {
add: function() {debugger;},
remove: function(){debugger;}
};
</script>
You can then, using chrome with the developer tools’ console open, navigate to the page and have the execution break every time a handler for YourCustomEvent is registered and unregistered.