📜 ⬆️ ⬇️

Where jQuery stores event handlers

In the "Internet" I did not find a detailed answer to this question. As a rule, it is recommended to use the standard method to get handlers:
$(elem).data('events') 

But in my case, he didn’t want to work, so I had to sort out the jQuery code a bit and find where they are stored after all.

So let's start in order.

1. All event data in jQuery is stored in the jQuery.cache variable
If we look there, we will see that this is a simple array of objects:
image
The element numbers in the array are the id’s of the specific objects to which this data belongs.
So how do you know which id, for example, from the document object?

2. The id of the jQuery object is stored inside the object itself in a special variable, the name of which is generated when jQuery is initialized.
And it is stored in jQuery.expando. Thus, the object id can be found as follows:
 elem[ jQuery.expando ] 

3. Now we know that the data for the object is stored in jQuery.cache, and we know how to get the id of the object. Get the jQuery data for our object:
 jQuery.cache[ elem[ jQuery.expando ] ] 

To receive events, you need to refer to the events of the object received above:
 jQuery.cache[ elem[ jQuery.expando ] ].events 

4. Next, you can get an array with objects where event handlers are stored, for example, for 'keydown', as follows:
 jQuery.cache[ elem[ jQuery.expando ] ].events['keydown'] 

5. We get an array of objects, each of which has a handler method - these are our event handlers:
image
')
As an example, we will output the installed handlers to the 'keydown' for the document object:
 var events = jQuery.cache[ document[ jQuery.expando ] ].events['keydown']; for(var i=0; i<events.length; i++) { console.log( events[i].handler ); } 

Result:
image

Source: https://habr.com/ru/post/200114/


All Articles