1

How can I check, if a event is handled with .on in jquery?
For example I have added an event handler to the button click event:

$(document).on("click", "#button", function(event)  {
    alert("Handled buttonclick event!");
});

Now I want to check if the event is handled to prevent assigning the same event handler a second time.

user2737037
  • 1,119
  • 1
  • 16
  • 29

2 Answers2

0

If you want to add a button click once only the you can use one() like,

$("#button").one("click",function(event)  {
    alert("Handled buttonclick event!");
});

or manually you can check by setting a variable like

var countClicked=0;
$(document).on("click", "#button", function(event)  {
    alert("You clicked button "+ (++countClicked) + " times");
});
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

Since you are delegating to the document - you need to check the document's event handlers

$._data(document,'events') // will return all event handlers bound to the document

Then you can do check the events you want.. for example click

var events = $._data(document,'events').click; // all click events

$.each(events,function(i,v){ // loop through
    v.selector; // will give you all the selectors used in each delegated event
});

http://jsfiddle.net/B7zS6/

each object will contain the following

Object {type: "click", origType: "click", data: undefined, handler: function, guid: 2…}
data: undefined
guid: 2
handler: function (event) {
namespace: ""
needsContext: false
origType: "click"
selector: "#button"
type: "click"
__proto__: Object

This is assuming your delegated events are bound to the document object though. So in this case you "MUST" know which element the event handler is actually bound to. The other answers will probably work a lot better

so this method would not know about

$('body').on("click", "#button", function(event)  {
    alert("Handled buttonclick event!");
});

or

$('parentelement').on("click", "#button", function(event)  {
    alert("Handled buttonclick event!");
});
wirey00
  • 33,517
  • 7
  • 54
  • 65