FtDRbwLXw6
FtDRbwLXw6

Reputation: 28929

jQuery - bind and execute a single handler?

I find myself often needing to bind an event handler, as well as immediately execute that handler in jQuery. To date, I've been using this lazy faux-pattern to keep the code DRY:

$(...).bind('event', function() {
    ...
}).trigger('event');

Today I was bitten by this, due to the fact that other handlers had already been bound to event, and they were also executed when I triggered the event in this way, but caused a lot of problems, since they weren't supposed to have been executed at that time.

To resolve the problem, I've changed the pattern to this:

var handler = function() {
    ...
};

var element = $(...);

element.bind('event', handler);
handler.call(element);

This works the way I expect, but it's ugly as sin and quite verbose, so I'm considering encapsulating this pattern into a jQuery plugin:

$(...).bindAndExecute('event', function() { ... });

I could find no equivalent for this in jQuery.bind() options or any of the other methods, but I may have missed something. Is there a more concise way of doing this that I haven't thought of? I don't want to reinvent the wheel.

Upvotes: 6

Views: 307

Answers (1)

kapa
kapa

Reputation: 78731

jQuery supports namespacing your events. This is a very useful technique and comes quite handy when you want unbind or trigger a specific group of events.

$(...).bind('event.myNamespace', function() {
    ...
}).trigger('event.myNamespace');

Using this technique is almost unavoidable (or at least sensible people won't avoid it) when you are developing bigger applications or jQuery plugins.

Quick jsFiddle Demo

Upvotes: 3

Related Questions