HTML and CSS Reference
In-Depth Information
The click events are assigned only to the <td> elements that are children of an element
named GameRow . jQuery provides advanced selector capabilities that allow fine control over
how the DOM is manipulated.
Implementing a callback with an anonymous function
Callback functions are used everywhere. The concept of a callback is the basis for how events
work. It's the mechanism by which asynchronous operations return to the caller. In traditional
programming languages, a callback is achieved by passing a pointer to a function to another
process so that when that process completes or is at specified stages of the process, the
function is called to advise the caller of a status of some sort. This could be when the opera-
tion completes and could be passing data back to the caller. An example of this would be an
asynchronous web service call that returns data. The principle is the same in JavaScript.
In JavaScript, functions are considered objects and are often noted as first-class citizens.
This means that a variable can be assigned a function, or a function can be passed into an-
other function as a parameter. Seeing functions used in this way is a common convention in
JavaScript. Functions used in this way are called anonymous functions.
A function is considered anonymous when it doesn't have a name. The following function
declaration has a name, so wouldn't be considered anonymous:
function SubmitClick() {
//do some logic here
}
Here a function is declared that can be used throughout the page. This function has
a name: SubmitClick . Because this function has a name, it's not an anonymous function.
However, a named function like this can be assigned to as many button events as you want:
$("#Button1").click(SubmitClick);
$("#Button2").click(SubmitClick);
$("#Button3").click(SubmitClick);
With a named function, the convenience of reuse is there. However, in some cases this
is more overhead than is necessary. This also can make the code more difficult to follow in
terms of being able to easily see what's actually happening in the click event handler. In a
situation that specifies distinct behavior for each button, anonymous functions simplify things
greatly. The following code demonstrates using anonymous functions instead of the named
function:
$("#Button1").click(function () { ... });
$("#Button2").click(function () { ... });
$("#Button3").click(function () { ... });
Each button is given its own function inline, where the implementation can be customized
for each button click. In that example, the use of anonymous function is apparent because the
function doesn't have a name. The syntax for an anonymous function is as follows:
function (n,n,…,n) { body };
 
 
Search WWH ::




Custom Search