HTML and CSS Reference
In-Depth Information
You don't need to worry about success or failure of each individual call or the order they respond in. You in-
stead get to wrap them up in a nice package and get a callback when all the remote calls are done. ( Deffered s
are documented at .)
Using Underscore.js
Although jQuery provides a number of utility methods that can make your life easier when writing JavaScript,
the main focus of jQuery is to modify the DOM and provide simplified Ajax support. It doesn't provide a lot
of utility methods for other purposes. (jQuery does provide some, though; see
utilities/ for some examples.)
Luckily, there's a library called the Underscore.js that was created for just that purpose. Underscore is a
small library (under 4 kb minified and gzipped) that provides approximately 60 methods that can make your
JavaScript easier to understand and more compact.
Accessing Underscore
Underscore.js is included in your project as a single JavaScript file, much like jQuery. Also similar to jQuery,
the author made the decision not to pollute the existing JavaScript namespace but rather to wrap all the methods
inside of a single function identified, not surprisingly, by the underscore character, " _ ".
You can call underscore methods in two ways either in a functional or an object-oriented style. Following is
an example of each:
The functional method calls the function directly on the underscore object, whereas the OO method first calls
the underscore on the target (much like jQuery does with selectors) and then calls the method on the resulting
Working with Collections
The bulk of the methods in Underscore.js are targeted at working with collections, whether they are arrays or
objects. Because much of what you do in game development is the manipulations of lists of objects such as
sprites, these methods come in handy. Say you have an array of objects called sprites and you want to call
the update() method on each of them in turn. You could write a for loop:
for(var i=0,len=sprites.length;i<len;i++) {
Alternatively with Underscore.js, this becomes
The latter method is both shorter and clearer about the intention of the code. The only downside is that there
is some overhead involved in calling an Underscore method instead of just writing your own loop. In most cases,
however, this overhead is negligible, and the advantage of smaller, more compact code is worth the trade-off.
Search WWH ::

Custom Search