USING UNDERSCORE.JS
jquery doesn't provide a lot of utility methods for other purposes.
small library approximately 60 methods that can make your Javascript easier to understand and more compact.
Accessing Underscore
underscore character _
function or object-oriented style
_.isString(myVar)
_(myVar).isString();
the OO method first calls the underscore on the target (much like jquery does with selectors)
and then calls the methods on the resulting object.
Working with Collections
the bulk of the methods in Underscore.js are targeted at working with collections
where they are arrays or objects. Because much of what you do in game developments is the manipulations of lists of objects such as sprites, these methods come in hnandy.
for(var i=0, len= sprites.length;i<len;i++) {
sprites[i].update();
}
_(sprites).invoke('update');
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.
this overhead is negligible, and the advantage of smaller, more compact code
iw worth the trade-off.
_.each(list,callback,[context])
Calls back each element of the list as an argument to the callback
use the native forEach in the browsers that support it.
context object that is bound to this inside the callback.
_.map(list,callback,[context]) takes the return values from the callbback
mthod and returns a new array
_filter(list,callback,[context]) Similar to _.find except that it returns an array
of all the items for which the callback returns true;
_without(array,[*array]) Returns a new array without any instances of values
removed;
_.uniq(array, [isSorted],[iterator]) _.uniq returns a copy of an array
with any duplicate elemnts removed. sorted state true to isSorted to improve
performance
Using Utility Functions
_.bindAll(object,[*methodNames])
Modifies any calls to methodNames on object so that the context
is always object.
_.keys(object) / _.values(object) Return all of an object's keys or values
_extend(destination,*sources) Copies all the properties from a list
of source objects over to the destination, overwriting any existing
properties.
_.is(ObjectType) check the type of a passed-in object. this
is useful beacuse JS does.nt provide built-in checking methods
_.isEqual, _.isEmpty, _.isElement,_.isArray, _.isFunction,_.isString,
_isNumber,_.isBoolean,_isNaN, _.isNull, and _.isUndefined,
_uniqueId([prefix]) generates a globally unique identifier for client-side
DOM elements or models
Chaining Underscore Method Calls
_(_(_(sprites)
.filter(function(s) {return s.category == "enemy";}))
.pluck('y'))
.max();
_.chain(sprites)
.filter(function(s){return s.category == "enemy";})
.pluck('y')
.max().value();