Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a callback in javascript

I am not so strong in javascript.

I have a common function that I call from many parts of my code passing them some parameters.

Can somebody help me on

  • how to define a new parameter for this function that should be a callback with no parameters passed from the caller (like many jquery plugins do)
  • how to handle the callback call inside the function

Giving advice regarding the solution, if there's a better one, etc.

thanks a lot!

like image 280
Lorenzo Avatar asked Oct 01 '10 17:10

Lorenzo


People also ask

How do I call a callback?

A custom callback function can be created by using the callback keyword as the last parameter. It can then be invoked by calling the callback() function at the end of the function. The typeof operator is optionally used to check if the argument passed is actually a function.

How do you pass a callback function in JavaScript?

Passing a function to another function or passing a function inside another function is known as a Callback Function. Syntax: function geekOne(z) { alert(z); } function geekTwo(a, callback) { callback(a); } prevfn(2, newfn); Above is an example of a callback variable in JavaScript function.

Why we use call back function in JavaScript?

Callback itself, as the name suggests (call - back) whenever you need to call a function after the execution of the first one, in those scenarios we need to use a callback.

What is call back and promise in JavaScript?

A callback function is passed as an argument to another function whereas Promise is something that is achieved or completed in the future. In JavaScript, a promise is an object and we use the promise constructor to initialize a promise.


1 Answers

It is actually quite simple.

function callback() {
    alert("I am in the callback!");
}

function work(func) {
    alert("I am calling the callback!");
    func(); 
}

work(callback);
like image 124
ChaosPandion Avatar answered Sep 30 '22 13:09

ChaosPandion