I often have to bind an event handler and also run this handler immediately in jQuery. To date, I have used this lazy faux pattern to save DRY code:
$(...).bind('event', function() { ... }).trigger('event');
Today I was bitten by this because the other handlers were already attached to the event
, and they were also executed when I called the event this way, but caused a lot of problems, since they were supposed to be executed at that time.
To solve the problem, I changed the template to this:
var handler = function() { ... }; var element = $(...); element.bind('event', handler); handler.call(element);
This works as I expect, but it is ugly as a sin and rather verbose, so I am considering encapsulating this template in a jQuery plugin:
$(...).bindAndExecute('event', function() { ... });
I could not find an equivalent for this in the jQuery.bind()
parameters or any other methods, but I might have missed something. Is there a more concise way to do this that I haven't thought about? I do not want to reinvent the wheel.
source share