Skip to content

Instantly share code, notes, and snippets.

@abalter
Last active April 21, 2016 17:20
Show Gist options
  • Save abalter/f6943270ac08095ce1e521f8ca4d3522 to your computer and use it in GitHub Desktop.
Save abalter/f6943270ac08095ce1e521f8ca4d3522 to your computer and use it in GitHub Desktop.

Callbacks

Callbacks are functions mostly used to handle the result of an action such as a query or a UI event, such as a click. And, especially in JQuery (worth learning--makes a lot of things super simple). They are especially important in situations that run asynchronously such as the two above examples.

Asynchronous operations

Asynchronous means that the interpreter does not wait for the action specified in a block of code to finish before continuing with the rest of the program.

For instance, when you query a server for data, you don't know how long, or if, the server will take to return the data. So the program does not wait. You create a callback function to run when the query does complete (successfully or unsuccessfully).

Another example is when you attach an event to a UI control. You don't know when that event will actually occur. So there is no point in running the code you want to have happen until the event occurs. Instead, you provide the event a callback function that runs when the event actually fires.

Queries

A query usuallly has at least two callback functions: (1) success and (2) error. In an AJAX request using JQuery (by far the simplest way), these can be put in as anonymous functions or named functions. In certain circumstances it's useful to have an anonymous function call a named function that does most of the work.

Here are two simple examples. They use the JSFiddle echo funcition for testing AJAX:

Anonymous Function

Events

Events are mostly used for UI controls.

Below are two buttons

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment