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!

quape
  • 726
  • 9
  • 21

3 Answers3

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

Dimitris Zorbas
  • 5,187
  • 3
  • 27
  • 33
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);

Nevyn
  • 56
  • 3