Callbacks
You seem to not understand how callbacks work. Let me explain. You have two events, one for keyup
on document
and the other on click
s on li
elements. These receive some function
s as parameters. At the point when your code runs, the functions you passed to the event handlers are only defined, but not executed, which is perfectly logical, because at that point no event occurs that would trigger them. The callbacks are therefore defined behaviors that are triggered when something happens.
So, the thing you misunderstand is that you mix up the definition of the event handlers with their execution. At the point of their definition they are not executed, however, just after their definition console.log
is being called for a variable which was not initialized yet due to lack of event triggering its initialization.
A callback is a function that your event calls "back" when it occurs.
For example if you call someone to ask him/her to come to you for a visit, it does not make sense to actively wait for them outside your door. It makes much more sense to agree when he arrives, he would call you back when his arrival, as an event happened. The behavior is very similar on a functional level in terms of callbacks
What happens after what:
$(document).on('keyup',function(e) { //when keyup on document, much later than the call of myFunction happened
if(e.which == 13) {
val = "keyup";
console.log(val);
}
});
$('#list li').click(function() { //when clicking on li, much later than the call of myFunction happened
val = "click"
console.log(val);
});
console.log('final val =' + val); //At the call of myFunction at page load
Final value
Since a keyup
on document
and a click
on the li
elements can happen any time, talking about a final value for val
does not make much sense. Since keyup
and click
are very rarely happen at the exact same time, determining a final value for val
at a given moment seems to be handling an edge-case. If that's what you want, then you can use a semaphore behavior.