I am binding a click event with a button:
$('#myButton').bind('click', onButtonClicked);
In one scenario, this is getting called multiple times, so when I do a trigger I see multiple ajax calls which I want to prevent.
How do I bind only if its not bound before.
Update 24 Aug ’12: In jQuery 1.8, it is no longer possible to access the element’s events using
.data('events'). (See this bug for details.) It is possible to access the same data withjQuery._data(elem, 'events'), an internal data structure, which is undocumented and therefore not 100% guaranteed to remain stable. This shouldn’t, however, be a problem, and the relevant line of the plugin code above can be changed to the following:jQuery events are stored in a data object called
events, so you could search in this:It would be best, of course, if you could structure your application so this code only gets called once.
This could be encapsulated into a plugin:
You could then call: