Tuesday, January 31, 2012

How to Access jQuery's Internal Data

As you may or may not be aware as of jQuery 1.7 the whole event system was rewritten from the ground up. The codebase is much faster and with the new .on() method there is a lot of uniformity to wiring up event handlers.

One used to be able to access the internal events data and investiate what events are registered on any given element, but recently this internal information has been hidden based on the following ticket...

"Ticket #8921: jQuery Private Data Should Stay Private

It seems that the "private" data is ALWAYS stored on the .data(jQuery.expando) - For "objects" where the deletion of the object should also delete its caches this makes some sense.

In the realm of nodes however, I think we should store these "private" members in a separate (private) cache so that they don't pollute the object returned by $.fn.data()"

--http://bugs.jquery.com/ticket/8921

Although I agree with the above change to hide the internal data, I have found having access to this information can be helpful for debugging and unit testing.


Thankfully, if you still need access to the internal data it is still accessible, however, you need to use a method that isn't officially documented... which means that you should be cautious about using it. I would encourage you to not use the undocumented ._data() method in production code.


You can view, run, and edit the above code sample from JSBin.

On the plus side, if you access the old .data() method with "events" as a parameter that will retrieve the internal data containing events and event handlers.

As a side note, if you are looking for events attached using the .live() or .delegate() methods then you will need to look at either the document element or whatever element you delegated against.

Update: Rick Waldron informed me on twitter that the jQuery Core team plans on creating a supported plugin to access the internal data that jQuery maintains. This would be a much better solution than using the above undocumented ._data() method because undocumented methods are also unsupported methods ;) I only use the ._data() method for debugging or testing. You should try to avoid using it in any of your production code for this reason.

1 comment:

  1. Don't ever use $._data() for any reason at all, ever. I will personally close every bug filed against it as "wontfix" without prejudice

    ReplyDelete