Difference between 'click', 'bind', 'live', 'delegate', 'trigger' and 'on' functions?

3

I gave a searched but there is not 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 of the above functions work exactly? Which should be prioritized in which situations?

    
asked by anonymous 28.09.2018 / 20:37

2 answers

6

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 stages , an event handler can know in which phase is through the property Event.eventPhase . The phases are:

  • CAPTURING_PHASE : event is propagated from window to target event element ( Event.target
  • AT_TARGET : event reached its target
  • BUBBLING_PHASE : event is propagated back to window .
  • These phases can best be viewed in the following image ( source ):

    AndnowyoualreadyknowwhattheuseCaptureparameterofthe method is for addEventListener , by default the handler intercepts the event in the bubbling phase, 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 with understanding ).

    Event delegation consists of assigning the handler of events from a target element to a parent element. That is, instead of the handler event being assigned to the target element and executed in the AT_TARGET phase, 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 have to exist when assigning the handler to the event, just the parent element. By having dynamically inserted elements on the page 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 becomes easier to explain the question.

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

    Let's call Listen to Events , Issue Events and Shortcuts .

  • 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 to an event via delegation. But the "parent element" is always document .
    • delegate (discontinued in jQuery 3.0, its use has been discouraged since jQuery 1.7): it also adds a handler for an event through delegation, only you can choose the "parent element".
    • on : this is the recommended method to use since it does what everyone else can do.

      You can assign handler to an event directly on the element. Ex.:

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

      Or delegate the event:

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

    • trigger : is the methods that you issue the event for handlers to call.
    • >
  • Shortcuts : These 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 for an event or $elemento.trigger('evento') when it is to broadcast the event.

    • click ;

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

      $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 ...

  • 28.09.2018 / 22:36
    3

    The live and delegate methods are old ways of delegating events, and have already been removed from the library. Delegation should now be done with the syntax:

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

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

    .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.

        
    28.09.2018 / 21:22