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.
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.
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.
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With