HTML and CSS Reference
In-Depth Information
Chaining Underscore Method Calls
Because Underscore does such nice things on collections, it would be nice if the syntax for dealing with multiple
calls to Underscore methods in a row were cleaner.
Following is an example of the problem. If you want to pull out the maximum y value of all the sprites of the
enemy category, you could write
_(_(_(sprites)
.filter(function(s) { return s.category == "enemy"; }))
.pluck('y'))
.max();
If you can follow all those nested _(..) calls, good luck; it's not something that is particularly readable.
For just this reason, Underscore provides a mechanism called chaining .
_.chain(sprites)
.filter(function(s) { return s.category == "enemy"; })
.pluck('y')
.max().value();
When you want to chain a number of underscore functions in a row, call _.chain() , and then when you
are done, call .value() .
Summary
Two useful JavaScript libraries—jQuery and Underscore—can help you write more compact code, devoid of
per-browser checks and boilerplate code, that is easier to understand and maintain.
Although not using a library is certainly an option ( Alien Invasion , after all, was built without libraries), the
cost of adding both jQuery and Underscore is less than 40 kb, or approximately the size of a small JPG. Take
advantage of the hard work that people have put in before you to make cross-browser development easier.
Search WWH ::




Custom Search