2

I'm trying writing down a function which will do something then bind a callback when finished, I would like to specify the callback when I init the js function...

function hello(arg1,arg2,callback){
    alert(arg1 + arg2);

   callback;
} 

hello('hello','world',function callback(){
    alert('hey 2);
});

sorry for banal question, I'm trying to understand how to pass a callback function to a function.

3 Answers 3

4

you need to call that function like anything else:

function hello(arg1,arg2,callback){
    alert(arg1 + arg2);

   callback();
} 

hello('hello','world',function callback(){
   alert('hey 2);
});

Note that in JavaScript there are better ways to execute that callback, like .apply() or call() but that is only required if you plan on using the this keyword inside callbacks.

Sign up to request clarification or add additional context in comments.

Comments

1

Inside of the function that you pass a function to, you have to invoke the passed function i.e.

function hello(arg1,arg2,callback){
  alert(arg1 + arg2);

  callback(); // invoke the function (this is just one way)
} 

hello('hello','world', function (){
  alert('hey 2');
});

You might go further and give the callback function a different context when calling it using Function.prototype.apply() or Function.prototype.call()

Comments

1

http://jsfiddle.net/wsNzL/

function A(a,b,func)
{
alert(a+b);
    func();
}

A(1,2,function(){alert("callback called");});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.