Skip to content

Instantly share code, notes, and snippets.

@apipkin
Created August 9, 2012 16:55
Show Gist options
  • Select an option

  • Save apipkin/3305855 to your computer and use it in GitHub Desktop.

Select an option

Save apipkin/3305855 to your computer and use it in GitHub Desktop.

Callbacks

Callbacks are functions that are called within another function. Because functions in javascript can be passed around through variables, this makes it pretty painless.

Setting it up

function myFn(callbackFn) {
    if (callbackFn) {
        (callbackFn());
    }
}

Now we have a function that's ready to take a function as a parameter and call it. We can do many things to this, but lets start off simple.

myFn(function() {
    alert('hi');
});

This will call the function and pass an anonymous function as the call back. When it's executed within myFn() it will alert "hi".

Do I have to use an anonymous function?

No. You can pass function names as well.

function myOtherFn() {
    alert('hello');
}
myFn(myOtherFn);

Or even

var myOtroFn = function() {
    alert('ohla');
};
myFn(myOtroFn);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment