1

A function triggers an event and passes on some data which then will possibly be processed by a listener. If not, the function wants to process the data by herself. Well, as I don't know if the package was handled or not, my idea was to find out if there is a listener at all. Is there a way to do this or does anyone have better ideas to my problem?

Thanks in advance!

6
  • Tried $(element).hasEventListener(type) ? May 12, 2013 at 9:01
  • Looks like that's a plugin: github.com/sebastien-p/jquery.hasEventListener
    – Barmar
    May 12, 2013 at 9:02
  • 1
    All events are binded to some elements. So in Chrome you have developer tools -> elements tab -> event listeners tab (in right side). Guess there is something similar in other browsers' devtools.
    – zelibobla
    May 12, 2013 at 9:04
  • What kind of listener are you talking about?
    – jfriend00
    May 12, 2013 at 9:05
  • 1
    This answere seems to show do what you want: stackoverflow.com/a/1515073/355499
    – Emil L
    May 12, 2013 at 9:16

3 Answers 3

2

You can to this with jQuery prior to 1.8 like this:

<script src="http://code.jquery.com/jquery-1.6.min.js"></script>

<script>
$(document).ready(function() {

$("#click_here").click(function() {
  alert("Handler for .click() called.");
});

 console.log( $('#click_here').data('events') );

});

</script>

<div id="click_here">Click here</div>
1

I created a plugin mainly to be used in your tests.

// Example usage
$('.foo').hasEvent('click', someHandler) 
// returns true if someHandler is bound via jQuery on '.foo' 
// for the click event

The plugin is tested to work with jQuery 1.7 and up

The plugin is hosted on github

1

I had a VERY similar problem. It's never been something that's been properly supported in jquery and instead was kind of a hack. So you could do it prior to version 1.8 in jquery by using

data('events')

After 1.8, you can use:

$._data( $('.element')[0], 'events' );

BUT if you're trying to do what I was doing... make sure an event handler is only assigned once on a control (i.e. a save button after some form validation), then you can either:

  1. Add a class and remove it to indicate whether an element has an event (ugly).
  2. Remove any handers before assigning it i.e.

$('element').unbind('event'); $('element').on('click', save);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.