JQuery - bind and execute a single handler?

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.

+6
source share
1 answer

jQuery supports namespacing your events . This is a very useful method and is useful when you want to unleash or trigger a specific group of events.

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

Using this technique is almost inevitable (or at least smart people won't shy away from it) when you develop larger jQuery applications or plugins.

JsFiddle quick demo

+3
source

Source: https://habr.com/ru/post/920157/


All Articles