views:

53

answers:

2

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?

+5  A: 

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

Jon Erickson
+1  A: 

While choice B would certainly be the way to do this if you needed to use a separate function, i.e., in the case where you needed to invoke the function from somewhere other than a button click, my preference is usually to put the code in line. The only other times I don't do this is when it would improve readability.

$(function() {
    $("button").click( function(e) {
        if (e.target.id == 'button1') {
           alert('button1 clicked');
        }
        ...
    });
});
tvanfosson