1

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());
}
6
  • 5
    When you pass in doit() as the callback, you Commented Aug 30, 2013 at 17:08
  • 1
    you... its like you enter the void ;) Commented Aug 30, 2013 at 17:08
  • 2
    that comment is very suspenseful. Commented Aug 30, 2013 at 17:09
  • 1
    @NULL Read rest of his answer to fill the void :) Commented Aug 30, 2013 at 17:22
  • 3
    I'm a fan of cliffhangers \o/ Commented Aug 30, 2013 at 18:33

4 Answers 4

8

You need to pass the function in as a parameter.

$("#me").on('keyup', 'input', doit);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Tried it and this does work: jsbin.com/IZecIj/1/edit But, I am still puzzled why this is the case. By the way, I had a typo in posted code, I had also tried 'doit'.
@MajidFouladpour Same works with an alert so try using alert instead of console.log.. may be jsbin overrides console.log? not sure
@Vega, console.log works fine; I had used 'doit' instead of doit.
6

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.

Comments

2

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.

2 Comments

Welcome to SO Rob! ;-)
YES. Although I've been around a little bit. This is one of the first non-ant question I've answered though.
1

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.