javascript call back function code example
Example 1: what is callback in function handler
Events - Think of a Server (Employee) and Client (Boss).
One Employee can have many Bosses.
The Employee Raises the event, when he finishes the task,
and the Bosses may decide to listen to the Employee event or not.
The employee is the publisher and the bosses are subscriber.
Callback - The Boss specifically asked the employee to do a task
and at the end of task done,
the Boss wants to be notified. The employee will make sure that when the task
is done, he notifies only the Boss that requested, not necessary all the Bosses.
The employee will not notify the Boss, if the partial job is done.
It will be only after all the task is done.
Only one boss requested the info, and employee only posted the
reply to one boss.
R: https://stackoverflow.com/a/34247759/7573706
Example 2: call back function in javascript
function greeting(name) {
alert('Hello ' + name);
}
function processUserInput(callback) {
var name = prompt('Please enter your name.');
callback(name);
}
processUserInput(greeting);
Example 3: callback function
function createQuote(quote, callback){
var myQuote = "Like I always say, " + quote;
callback(myQuote); // 2
}
function logQuote(quote){
console.log(quote);
}
createQuote("eat your vegetables!", logQuote); // 1
// Result in console:
// Like I always say, eat your vegetables!