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());
}
You should pass the function, not call it
To clear why that is wrong, see this example:
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.
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 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:
You need to pass the function in as a parameter.
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 (likelyundefined
) as the callback. If you pass in just a reference to the named functiondoit
then the function will be executed as the callback.