Majid Fouladpour
Majid Fouladpour

Reputation: 30242

Using defined function instead of anonymous function as callback

Why isn't it possible to use a defined function as event callback?

<div id="me">
  <input>
</div>

$(document).ready(function(){
  // $("#me").on('keyup', 'input', doit()); # doesn't work
  // $("#me").on('keyup', 'input', 'doit'); # neither does this
  $("#me").on('keyup', 'input', function() {
    doit();
  }); // well, this one works of course
});

function doit() {
  console.log($("input").val());
}

Upvotes: 1

Views: 167

Answers (4)

tymeJV
tymeJV

Reputation: 104775

You need to pass the function in as a parameter.

$("#me").on('keyup', 'input', doit);

Upvotes: 8

roblarsen
roblarsen

Reputation: 452

When you pass in doit() (with the "()") as the callback, you're actually running the function at that point and passing in the return value of the function (likely undefined) as the callback. If you pass in just a reference to the named function doit then the function will be executed as the callback.

Upvotes: 2

user980058
user980058

Reputation: 511

when you say something=function(){ blah } in js, it stores that as text and parses it on the fly - so yes, you can. For example:

CallMe = function(){ alert("blah!"); }
bobsCallback.setFunction( CallMe );

CallMe is like any other variable, but it's contents is the js for the function. You can pass it around as a callback, or invoke like so:

alert("calling CallMe...");
CallMe();

Upvotes: 1

Alberto Zaccagni
Alberto Zaccagni

Reputation: 31560

You should pass the function, not call it

$("#me").on('keyup', 'input', doit)

To clear why that is wrong, see this example:

$("#me").on('keyup', 'input', (function() {
  doit();
})()); 

Here you are passing an anonymous function and invoking it immediately, which is not what the event handler expects.

The problem is not in the difference between anonymous or not, the problem is that you are invoking the function instead of passing it.

Upvotes: 6

Related Questions