HTML and CSS Reference
In-Depth Information
Some of the most common and helpful methods are documented in the following list.
•
_.each(list, callback, [context])
:
Calls back each element of the list as an argument to
the callback. It uses the native
forEach
in the browsers that support it. Notice
_.each
takes an addi-
tional “context” object that is bound to
this
inside the callback.
•
_.map(list, callback, [context])
: Similar to
_.each
, except it takes the return values
from the callback method and returns a new array.
•
_.find(list, callback, [context])
:
Returns the first item in the list for which the callback
function returns
true
. It's useful for finding an element in a list based on some arbitrary criteria func-
tion.
•
_.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, [*values])
:
Returns a new array without any instances of values removed;
useful, for example, for removing dead sprites from a list.
•
_.uniq(array, [isSorted], [iterator])
:
_.uniq
returns a copy of an array with any
duplicate elements removed. If the array happens to be in a sorted state, pass
true
to
isSorted
to
improve performance.
Taken together, these methods make working with lists of objects much more concise.
Using Utility Functions
Underscore also provides a number of general utility functions that can make your life easier.
•
_.bindAll(object, [*methodNames])
:
Modifies any calls to
methodNames
on
object
so
that the context is always
object
. This means you can pass methods to jQuery event handlers, for ex-
ample, without needing to worry about the context of
this
.
•
_.keys(object) / _.values(object)
:
Returns 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]
:
Underscore.js provides a good number of methods of the form
_.is[Ob-
jectType]
to check the type of a passed-in object. This is useful because JavaScript doesn't provide
built-in type checking methods. The methods Underscore provides are
_.isEqual
,
_.isEmpty
,
_.isElement, _.isArray
,
_.isFunction
,
_.isString
, _
isNumber
,
_.isBoolean
,
_.isNaN
,
_.isNull
, and
_.isUndefined.
All the
_.is[ObjectType]
methods are relatively
self-explanatory: They each check the type of the object passed in and return
true
or
false
. They
provide a succinct way to do type checking on JavaScript objects, which is useful for checking arguments
and faking polymorphism by having methods behave differently depending on what is passed into them.
•
_.uniqueId([prefix])
:
Generates a globally unique identifier for client-side DOM elements or
models. This is useful because you often want to add unique ID attributes to elements you add to the
page.
These utility methods, particularly
_.extend
are used frequently in the topic.