Search code examples
javascriptjqueryevent-delegation

Correct syntax for defining an event delegator


Normally you write a handler for a button click like this:

$(document).ready(function()
{

  $("button").click(function()
  {    
    doSomething();
  });
});

But in the case of an event delegator, to respond to an event with a function such as this:

  function doSomething(event)
  {
    if (ev.target.id == 'button1' )
    {
       //do your stuff
       console.log('#button1 click');
    }
    else
    {
       console.log('not a #button1 click');
    }
  }

What I'm confused about is the correct syntax for defining the event that calls this delegator function - this? (A):

$(document).ready(function()
{
  $(function()
  {
    $('button').click(doSomething);
  });
});

or this? (B):

$(document).ready(function()
{
  $("button").click(doSomething);
});

Which is correct and why?


Solution

  • In choice A you are just repeating the document.ready syntax twice.

    // These two lines are equal
    $(document).ready(fn);
    $(fn);
    

    All you need to do is choice B