In jQuery, I do stuff like this a lot:
$('#myId').bind('myevent', function() { ... }).trigger('myevent');
Works great when the selector only finds one element, but I don’t want it to fire more than once if there’s more than one match.
Is there some way to basically declare an anonymous function and execute it exactly once all in one swoop?
Or do you have to make it non-anonymous (give it a name), pass it in, and call it once manually?
For example, I might bind a .change event to set of radio buttons. In the callback, I check which one is actually set and then show/hide a div. When the page loads, the div needs to be in the correct state, so I fire the event once and let the JS figure out whether or not it should be shown. But I don’t really want it to fire 3 times because I’ve got 3 radio buttons.
Use the
triggerHandler()[docs] method instead of thetrigger()[docs] method.This will invoke the handler only once, and will not allow the event to bubble or trigger the default behavior.
From the docs: