0

I have a jQuery function:

$(".foo").click(function(event) {
  console.log(event.type);
});

I'd like to extract the function:

function logEventType(event) {
  console.log(event.type);
}

When I try to call it with the parameter:

$(".foo").click(logEventType(event));

it runs automatically on page load and doesn't operate on click function. However, if I call it without the parameter:

$(".foo").click(logEventType);

it runs exactly like I'd hope. I guess I have it working fine, but I'm just wondering what's going on and why.

Rob
  • 14,746
  • 28
  • 47
  • 65
  • There's a difference in calling a function, and referencing a function that *will be called later*. When you add parentheses you call the function, always, and return the result, which would be `undefined` unless you've specified another return value from the function, so you're basically doing `$(".foo").click(undefined);`, which won't work, all you want is a reference to the function, which you get by just using it's name. – adeneo May 07 '16 at 21:39
  • this *must* be a repeat of many other questions - simple answer - you have to pass the function reference, not the _result of calling the function_ – Alnitak May 07 '16 at 21:40
  • Because in the second example you're passing the reference to the function rather than calling it immediately which is how it works. See also `setTimeout(fn(), 1000)` and `setTimeout(fn, 1000)`. The latter is the correct version. – Andy May 07 '16 at 21:41
  • 1
    "I'm just wondering what's going on and why." It's the nature of callbacks. You pass the reference to the function, without the parameters. Much like with delegates and event delegations, it infers the signature — it knows which arguments will be passed and resolve them when you click. – napo May 07 '16 at 21:43
  • If you inline the function again, `$(".foo").click(logEventType(event));` becomes `$(".foo").click(function(event) { console.log(event.type); }(event));`. Since you are not doing this in your first example either, why would you add `(event)` later? – Felix Kling May 07 '16 at 23:01

1 Answers1

-1

.click expects anonymous func or callback func. when you pass func(), it executes immediately. But we pass callback func, the jquery will call this func when the associated event occurs with event parameter,so you can get access that parameter

Karthik M R
  • 980
  • 1
  • 7
  • 12