Friday, September 3, 2010

A brief dialogue on Callback Functions

Often when you are writing jQuery methods you will notice that you can include a special parameter called the callback function. This can be additional code that you can have run after the effect has been run on whatever method you are using. So for example say we are going to toggle a message:

$('#toggledMessage').toggle('fast', function() { alert('The message has just been toggled') } );

Normally we would have just ended with the 'fast' parameter but we included an additional function after it to be run. In this case the callback function is simply going to generate an alert notifying us that the effect has been toggled. This is a simple example, but we could call much more complex function calls in our calback method.

An important point on this is that these callbacks are refered to as anonymous functions because we are simply calling a generic function in this example that generates an alert message and not assigning it a name. This can be typically be used fairly safely as long as we only use it one place. However, a better idea as you get more famliar with jQuery is to pass a function name and define that function elsewhere in your code. It keeps it cleaner but certainly an anonymous function will work in most examples.

No comments:

Post a Comment