I have an ajax app that will run functions on every interaction. I'd like to be able to run my setup function each time so all my setup code for that function remains encapsulated. However, binding elements more than once means that the handler will run more than once, which is obviously undesirable. Is there an elegant way in jQuery to call bind on an element more than once without the handler being called more than once?
+4
A:
You could attach the event to document with the one() function:
$(document).one('click', function(e) {
// initialization here
});
Once run, this event handler is removed again so that it will not run again. However, if you need the initialization to run before the click event of some other element, we will have to think of something else. Using mousedown instead of click might work then, as the mousedown event is fired before the click event.
Tom Bartel
2010-06-01 04:10:10
You're missing a `);` in there.
Ben
2010-06-01 04:14:02
Oh thanks Ben, fixing...
Tom Bartel
2010-06-01 04:15:36
Didn't know of this one.
DMin
2010-06-01 04:27:31
This will only solve his problem partially. Attaching events using `one` multiple times will still run multiple times, but once each.
Chetan Sastry
2010-06-01 04:40:05
@Chetan: I don't quite understand. There is only one `document` object (to which the event bubbles up), so how am I attaching the event multiple times?
Tom Bartel
2010-06-01 04:57:26
@Tom see http://jsfiddle.net/P6aUT/2/ .. each time you click on `Attach click handler` and then click anywhere in the document, the attached event handler will get executed *once*. Also, attaching the event handler to document is no different from attaching it to any other element.
Anurag
2010-06-01 05:04:28
Reading the question again, it is not entirely clear to me. Why the need to bind an event handler to an element more than once?
Tom Bartel
2010-06-01 07:07:00
@Tom - that is a good point. Binding the event handlers again because the Javascript initialization code needs to run on every interaction sounds like it would require a lot of patchwork. A better solution might be to reset the state of the application (including removing all event handlers as @Chetan suggested) to the initial state instead of trying to preventing binding the same handlers again.
Anurag
2010-06-01 09:29:42
+1
A:
User jQuery one function like Tom said, but unbind the handler each time before binding again. It helps to have the event handler assigned to a variable than using an anonymous function.
var handler = function(e) { // stuff };
$('#element').unbind('click', handler).one('click', handler);
//elsewhere
$('#element').unbind('click', handler).one('click', handler);
You can also do .unbind('click') to remove all click handlers attached to an element.
Chetan Sastry
2010-06-01 04:44:19