开发者

How do I access what events have been bound to a dom element using only JavaScript, no frameworks

How do I acces开发者_运维百科s what events have been bound to a DOM element using JavaScript and NOT using a library/framework or Firefox add-on? Just pure JavaScript. I incorrectly assumed there would be an events object stored as a property of the element which has the binding.

For example if I had bound say, click, dblclick and mouseover to an element how would I do the following NOT using jQuery. Just JavaScript.

function check(el){
 var events = $(el).data('events');
 for (i in $(el).data('events')) {
  console.log(i) //logs click dblclick and mouseover
  }
}

I know jQuery stores an events object as a data property i.e. $(el).data('events') and the eventbug add-on displays the event binding so there must be way.

I will also add that this question came about because I read about memory leaks in older IE browsers and how it's best to remove the bound events before removing a node from the DOM, which lead me to think, how can I test for what events are bound to an element?


You can't reliably know what listeners are on an element if you aren't in complete control of the environment. Some libraries manually control event listeners, e.g. jQuery stores them in an object and adds a custom attribute to the element so that when an even occurs, it uses the custom property to look up the listeners for that element and event and calls them.

Try:

<div id="d0">div 0</div>
<script type="text/javascript">

var el = document.getElementById('d0')
el.addEventListener('click',function(){alert('hey');},false);

// Make sure listener has had time to be set then look at property
window.setTimeout(function(){alert(el.onclick)}, 100); // null

</script>

So to know what listeners have been added, you need to be in complete control.

Edit:

To make it clear, there is no reliable way to inspect an element with javascript and discover what listeners have been added, or even if any have been added at all. You can create an event registration scheme to track listeners added using your event registration methods. But if listeners are added some other way (e.g. directly by addEventListener) then your registration scheme won't know about them.

As pointed out elsewhere, jQuery (and others) can't track listeners that are added directly to elements without using the jQuery event registration methods (click, bind, mouseover, etc.) because they use those methods to register (and call) the listeners.


// list of onevent attributes; you'll have to complete this list
var arr = ['onclick', 'onmouseover', 'onmouseup'];

for ( var i = 0; i < arr.length; i++ ) {
    if ( el[arr[i]] != null ) {
        // element has an arr[i] handler
    }  
}

where el is a reference to your DOM element

Complete lists are here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜