Difference between click, bind, live, delegate, Trigger and on functions?

Asked

Viewed 213 times

3

I did a search but there is a comparison list between the functions below:

$().click(fn)
$().bind('click', fn)
$().live('click', fn)
$().delegate(selector, 'click', fn)
$().trigger('click') 
$().on('click', selector, fn);

How do all the above functions work exactly? Which should be prioritized in which situations?

2 answers

10


All these functions are event-related. So we need to understand some concepts to go forward.

Event Phase

When an event is issued it has 3 phases, an event Handler can know what stage is through the property Event.eventPhase. The phases are:

  1. CAPTURING_PHASE: the event is propagated from window to the target element of the event (Event.target)
  2. AT_TARGET: the event has reached its target
  3. BUBBLING_PHASE: the event is propagated back until window.

These phases can be better visualized in the following image (source):

Fases de propagação de um evento

And now you know what the parameter is for useCapture of the method addEventListener, by default the Handler intercepts the event in the phase of Bubbling, but you can change this through this parameter. ;)

Delegation

Knowing this, we now need to understand what it means to delegate an event (this is a good article to help in understanding).

The delegation of events is to assign the Handler events from a target element to a parent element. I mean, instead of Handler the event be assigned to the target element and be executed in the AT_TARGET, it will be assigned to a parent element of this target element and will be executed in phase CAPTURING_PHASE or BUBBLING_PHASE.

What is the advantage of this? The main advantage is that the target element does not need to exist when assigning the Handler event, only the parent element. Causing elements dynamically inserted in the page to react to delegated events without having to assign a Handler to each of them.

A quick example to illustrate how this works:

let pai = document.querySelector('#elemento-pai');

pai.addEventListener('click', function(event) {
  // #pai não é alvo, mas está interceptando o evento
  // na fase de bubbling
  if (event.target.classList.contains('elemento-alvo')) {
    event.target.classList.toggle('active');
  }
});

// adiciona itens dinamicamente à lista
let btn = document.querySelector('#add');
btn.addEventListener('click', function() {
  let li = document.createElement('li');
  li.className = "elemento-alvo";
  li.innerHTML = "Item dinâmico";
  pai.appendChild(li);
});
.elemento-alvo.active {
    color: red;
}
<ul id="elemento-pai">
  <li class="elemento-alvo">Item</li>
  <li class="elemento-alvo">Item</li>
</ul>
<button id="add">+</button>

Now that the concept of event delegation is clearer, it’s easier to explain the question.

Let’s start by dividing the methods into categories (or by functionality, or whatever).

Let’s call it: Listen to events, Issue Events and Shortcuts.


  1. Listen to events:

    • bind (Discontinued in jQuery 3.0): Adds a Handler for an event in the element (phase AT_TARGET).
    • live (Discontinued in jQuery 1.7): Add a Handler for an event through delegation. But the "parent element" is always document.
    • delegate (Discontinued in jQuery 3.0, its use is discouraged since jQuery 1.7): it also adds a Handler for an event through delegation, only it is possible to choose the "parent element".
    • on: is the recommended method to be used, since it does what everyone else can do.

      You can assign Handler for an event directly in the element. Ex.:

      $('#btn').on('click', myHandler)
      

      Or delegate the event:

      $('#elemento-pai').on('click', '.elemento-target', myHandler)
      
  2. Issue events:

    • Trigger: is the methods that you issue the event so that the handlers be called.
  3. Shortcuts: They are methods to facilitate the use of some commonly used methods. In general $elemento.evento(...) is equivalent to $elemento.on('evento', handler) when used to listen to an event or $elemento.trigger('evento') when is to issue the event.

    • click;

      $elemento.click(function(){});
      // mesmo que
      $elemento.on('click', function(){});
      
      $elemento.click();
      // mesmo que
      $elemento.trigger('click');
      
    • phocus;

      $elemento.focus(function(){});
      // mesmo que
      $elemento.on('focus', function(){});
      
      $elemento.focus();
      // mesmo que
      $elemento.trigger('focus');
      
    • Blur;

      $elemento.blur(function(){});
      // mesmo que
      $elemento.on('blur', function(){});
      
      $elemento.blur();
      // mesmo que
      $elemento.trigger('blur');
      
    • other events...

  • +1, much more detailed than my reply I wrote in a hurry :)

  • Once you understand, it’s easy, but it’s hard to explain. I knew the differences but when I started writing and it took too long I was going to release a reduced version. Then you had already posted your reply and decided to follow in the toil. : D

4

The methods live and delegate are old forms of event delegation, and have already been removed from the library. Currently you should delegate with the syntax:

$('seletor').on('evento', 'outro-seletor', callback);

Already $('seletor').click(fn) is simply a shortcut to $('seletor').on('click', fn). The bind is also an old form that has been removed from the library, and replaced by .on.

The .trigger does the opposite of all these other methods. As the name says, it triggers an event. Already .on and shortcuts like .click treat events triggered by third parties.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.