0

I am using jQuery v1.7.1 and binding events to elements as in the following example:

<input id="testTextBox" name="testTextBox" type="text" value="" />

<script type="text/javascript">
    function evtHandler() {
        alert("Event fired!");
    }

    $(function() {
        $("#testTextBox").bind("change", evtHandler);
    });
</script>

Obviously my page has a lot more controls than this, including some Ajax to replace parts of the page. So during testing I would like to have a simple way to see if events bound successfully. I know I can check $("#testTextBox").length before binding to determine if the control was found, but is that the best and only way?

Nameless One
  • 1,615
  • 2
  • 23
  • 39
  • 1
    What's the point of it? – Felix Kling May 31 '13 at 10:32
  • As I said, it is mostly for testing purposes, i.e. making sure in the 40+ events binding on my page I have no typos and the controls are available (after some server-side logic was applied) for all the scenarios allowed by the business logic. – Nameless One May 31 '13 at 10:52

2 Answers2

3

The only reason an event won't bind is if the DOM element doesn't exist.

You could trap this by shimming the .on method (don't use .bind - it's obsolete, although the technique below would still work):

(function($) {
    var _on = $.fn.on;

    $.fn.on = function() {
        if (this.length) {
            return _on.apply(this, arguments);
        } else {
            throw new Error('.on called on empty jQuery object');
        }
    };
})(jQuery);

For testing purposes you could also extend this function to test for duplicate event registration by checking for existing handlers in each element's .data('events') data, as mentioned by @paulitto. However be aware that this is digging into jQuery internals which may change in future versions.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
1

For your version of jquery you can also check element's 'events' jquery data

This would throw events bound to testTextBox to console as an Object:

console.log($('#testTextBox').data('events'));
paulitto
  • 4,585
  • 2
  • 22
  • 28
  • Out of date, see the later answers at http://stackoverflow.com/questions/1236067/test-if-event-handler-is-bound-to-an-element-in-jquery – Noumenon Oct 30 '15 at 04:26