Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - bind and execute a single handler?

Tags:

jquery

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.

like image 688
FtDRbwLXw6 Avatar asked Jul 10 '12 19:07

FtDRbwLXw6


People also ask

How do I run a function only once in jQuery?

jQuery one() method The one() method attaches one or more event handlers for the selected elements and specifies a function to run when the event occurs. When using the one() method, the event handler function is only run Once for each element.

What is the difference between bind () and live () method in jQuery?

In short: . bind() will only apply to the items you currently have selected in your jQuery object. . live() will apply to all current matching elements, as well as any you might add in the future.

What does .bind function do in jQuery?

bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .


1 Answers

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

like image 51
kapa Avatar answered Nov 15 '22 08:11

kapa