Reputation: 248
I started web development recently, and i can't seem to wrap my head around event handlers and callback functions. I understand that events handlers are a type of callback, and they respond to events unlike the more general definition of callbacks that get called by some other code when it finishes running. But, I'm looking for an explanation that 'sticks' with me.
Here's an example
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
});
</script>
In this code example, i know that ready and click are both events so $("button").click(function(){
is an event handler for the ready event? and $("p").hide("slow", function(){
is an event handler for the click event? How about hide? is it also an event?
Upvotes: 0
Views: 848
Reputation: 9128
Callback functions are what you described. Functions that are passed as parameters to another function and then later "called back".
Example:
file.read(fileName, function (err, data) {
// once file reading has finished, this function body is called,
// so this anonymous function is the callback
});
Event handlers are functions that gets triggered when a specific event occurs. It can be used for synthetic events, websocket events, and more. And its usual syntax is using callbacks.
Examples:
eventBus.on('new_message_arrived', function (err, data) {
// when 'new_message_arrived' event happens, this callback will be called
});
button.click((event) => {
// when button gets clicked, this callback (now used arrow function notaion)
// will be called with the details of the UI event
});
Upvotes: 1
Reputation: 1074266
Yes, that's correct (took me a second to realize you were just showing the content of the handlers you were referring to). It's clearer if you don't define the handlers/callbacks inline, and you give them descriptive names:
function readyHandler() {
$("button").click(clickHandler);
}
function clickHandler() {
$("p").hide("slow", hideAnimationCompleteCallback);
}
function hideAnimationCompleteCallback() {
alert("The paragraph is now hidden");
}
$(document).ready(readyHandler);
Note that the code above is slightly different from your original, which looks more like this:
function readyHandler() {
function clickHandler() {
function hideAnimationCompleteCallback() {
alert("The paragraph is now hidden");
}
$("p").hide("slow", hideAnimationCompleteCallback);
}
$("button").click(clickHandler);
}
$(document).ready(readyHandler);
...but since none of the handlers/callbacks was relying on the fact it was created inside a handler/callback, it seemed clearer to show them completely independently. But it would matter if they were using something that's only in-scope within the handler they were created in.
Upvotes: 1