HTML and CSS Reference
In-Depth Information
Why are anonymous functions becoming so popular? The primary reason is that anonymous
functions allow you to define code in place—without the need to define a named function
somewhere. The drawback of anonymous functions is that they are not reusable. As long as you need
to pass a one-off piece of code as an argument, then using an anonymous function is more than
acceptable. However, if the function might be used more often, a named function is preferable. Just
for the sake of illustration, here's a rewrite of the previous code using anonymous functions:
// Perform a sum
handleNumbers(function(numbers) {
var result = 0;
for (var i = 0; i < numbers.length; i++) {
result += numbers[i];
}
return result;
},
1, 2, 3, 4);
Readability is not always ideal; but for very basic code, this approach can still work.
Organizing your own JavaScript code
So far, you have focused primarily on the syntactic aspects of the JavaScript language, and you've
explored JavaScript's object-oriented capabilities. It is now about time to shift to how you use
JavaScript code from within HTML pages, and specifically, in the context of Windows 8 applications.
Any JavaScript code you use in an HTML page is always invoked in response to an event that is
either fired by the browser or fired in response to some user action. Hence, the first point to focus
on is how to define event handlers in an HTML page. Next, you need to know a little about how to
organize the code.
Linking JavaScript code to pages
First and foremost, an event handler is a JavaScript function invoked in response to an event. The
event can be fired by the browser—for example, the browser fires an event when the page has fully
loaded—or in response to an action by a person—for example, when a user clicks a button. Event
handlers must be associated with events to produce any visible effects. HTML defines a number of
onXXX attributes (where XXX is the name of the event, such as click or load ) that you can set in the
HTML markup to associate the event with the name of a JavaScript function.
Unobtrusive JavaScript is a pattern that suggests a more effective way of achieving the same result.
Unobtrusive JavaScript is also the preferred way of binding code to events in Windows 8. Let's find
out more.
Search WWH ::




Custom Search