Event delegation in jQuery - which method is better?

In an attempt to write better code and improve how I use jQuery, I recently did the reading. One of the new tips that I learned is to use event delegation with jQuery.

While reading, I discovered two โ€œallegedโ€ different methods of accessing it. The following are snippets of code to illustrate them.

Assuming I have an HTML block as follows:

<html>
  <head>
    <title>Test Code</title>
  </head>
  <body>
    <div id="switcher">
      <button id="button1">Button 1</button>
      <button id="button2">Button 1</button>
      <button id="button3">Button 2</button>
      <button id="button4">Button 3</button>
      <button id="button5">Button 4</button>
      <button id="button5">Button 5</button>
      <button id="button6">Button 6</button>
      <button id="button7">Button 7</button>
      <button id="button8">Button 8</button>
      <button id="button9">Button 9</button>
    </div>
<!-- rest of code here -->
  </body>
</html>

In a click, I want:

  • Get the identifier of the pressed button (for further manipulations).
  • Switch the class to โ€œactiveโ€ for any of the buttons.

Instead of this:

$('#switcher').find('button').click(function(){
  var $element = $(this);      
  var elementid = this.id;
  $element.toggleClass('clicked');
  //rest of code here
});

I can either do it (method 1)

$('#switcher').click(function(eventName){
  if ($(eventName.target).is('button')) {
    var $element =$(eventName.target);
    var elementid = eventName.target.id;
    $element.toggleClass('active');
    //rest of code here
  }
});

Or this (method 2)

$('#switcher').on('click', 'button', function(){
  var $element = $(this);
  var elementid = this.id;
  $element.toggleClass('active');
  //rest of code here
});
  • Are these 2 actually both delegation technologies?
  • , ( ) ?
  • ?
+4
1

button ( ), ( , , ).

:

<div id="switcher">
      <button id="button1">Button 1</button>
      <button id="button3">Button 2</button>
</div>

DOM , :

<div id="switcher">       
    <button id="button1">
        <div class="inner">Button 1</div>
    </button>
    <button id="button3">
        <div class="inner">Button 2</div>
    </button>
</div>

... "" jQuery .

jQuery , . , . - : click. , , , , , ( -, ).

, ( ?) . . RequestAnimationFrame, , . , click , , ( !) DOM: , , , .

0

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


All Articles