5. âUnderscore is a utility-belt
library for JavaScript âŠ
without extending any of the
built-in JavaScript objects.
It's the tie to go along with
jQuery's tux, and
Backbone.js's
suspenders.â
11. Caution: CoffeeScript
CoffeeScript
â â⊠a little language that compiles into JavaScriptâ
Concise and readable
Optional parenthesis
Implicit returns
Concise function deïŹnitions
Great ïŹt with Underscore!
16. Useful Predicates
Predicate Description
isEmpty Is the value null, undeïŹned, the empty string, an empty object, or an empty array?
isElement Is the value a DOM element?
isArray Is the value an array (but not arguments)?
isArguments Is the value the special arguments object?
isFunction Is the value a function?
isString Is the value a string?
isNumber Is the value a number
isBoolean Is the value a boolean?
isDate Is the value a JavaScript Date?
isRegExp Is the value a Regular Expression
isNaN Is the value NaN (note: returns false for undeïŹned)
isNull Is the value null (but not undeïŹned)
isUndeïŹned Is the value speciïŹcally undeïŹned
22. _.each(list, iterator, [context])
this set to context before invoking iterator
_.each ["alpha", "bravo", "charlie"],
(value, index) ->
console.log "#{value} is at #{index}"
alpha is at 0
bravo is at 1 More CoffeeScript goodness
charlie is at 2
â undefined
Alias: _.forEach
23. iterator function
Callback function passed to Underscore functions
Iterating arrays
value
index
array being iterated
Iterating objects
value
key
object being iterated
24. context and this
this is a side-effect of method invocation:
anObject.aMethod() â var fn = anObject["aMethod"];
fn.call(anObject)
Sets this for new stack frame
DOM and JQuery manipulate this
â Usually the DOM element that triggered event
this not relevant to HOFs
Functions, parameters, local scope
Optional context parameter on many _ functions
25. _.each(object, iterator, [context])
_.each me, (value, key) ->
console.log "Value for #{key} is #{value}"
Value for firstName is Howard
Value for lastName is Lewis Ship
â undefined
26. _.each(list) and undeïŹned
sparse = []
sparse[10] = "ten"
sparse[20] = "twenty"
_.each sparse, (value, index) ->
console.log "#{value} is at #{index}"
"ten is at 10"
"twenty is at 20"
â undefined
27. _.map(list, iterator, [context])
_.map [1, 2, 3], (value) -> 2 * value
â [2, 4, 6]
_.map [1, 2, 3, 40, 500],
(value, index) -> value * index
â [0, 2, 6, 120, 2000]
_.map me,(value, key) ->
"Value for #{key} is #{value}"
â ["Value for firstName is Howard",
"Value for lastName is Lewis Ship"]
Alias: _.collect
41. _ is a function
Every function on _ is also on
Returns a wrapper object wrapper object
_(hand).pluck "value"
â [3, 2, 7, 8]
Wrapped object passed as ïŹrst parameter
_(hand).size()
â 4
42. Chaining Can Be Ugly
_.map(_.first(_.sortBy(hand,cardSortValue).reverse(), 2),
   (card) -> "#{card.value} of #{card.suit}")
â ["8 of diamonds", "7 of spades"]
1.Sort the hand using the cardSortValue function
2.Reverse the result
3.Take the ïŹrst two cards
4.Convert each card to a string
43. _.chain(object) and _.value(object)
_.chain(hand)
.sortBy(cardSortValue)
.reverse()
.first(2) Each step returns a new wrapped object
.map((card) -> "#{card.value} of #{card.suit}")
.value()
â ["8 of diamonds", "7 of spades"]
48. Name Description Aliases
ïŹrst(array) Return ïŹrst element in array, as single value head
ïŹrst(array, n) Return ïŹrst elements of array as list head
initial(array, [n]) Return everything but last n (default = 1) elements of array
last(array) Return last element in array, as single value
last(array, n) Return last n (default = 1) elements of array
rest(array, [n]) Return array from index n (default = 1) on tail
indexOf(array, value, [isSorted]) Index of value inside array, or -1
lastIndexOf(array, value) Last index of value inside array, or -1
Returns copy with all falsey (null, false, 0, undeïŹned, NaN)
compact(array)
removed
ïŹatten(array, [shallow]) Collapses nested arrays down to a single array
55. _.defer(function)
do invokes the function with no parameters
do ->
_.defer -> console.log "deferred"
console.log "immediate"
immediate
â undefined
deferred
56. _.delay(fn, wait, [*arguments])
log = _.bind console.log, console
do ->
_.delay log, 1000, "delayed"
log "immediate"
immediate
â undefined
delayed
About 1 second later
57. _.wrap(function, interceptor)
timerInterceptor = (wrapped, args...) ->
start = Date.now()
result = wrapped(args...)
elapsed = Date.now() - start
console.log "Function call took #{elapsed} ms."
return result
fib = (x) ->
switch x
when 0 then 0
when 1 then 1
else fib(x - 1) + fib(x - 2)
tfib = _.wrap fib, timerInterceptor
tfib 30
Function call took 23 ms.
â 832040
tfib 40
Function call took 2674 ms.
â 102334155
58. More Functions on Functions
bindAll
memoize
throttle
debounce
once
after
compose
59. Underscore Utilities
Name Description
identity(value) Returns its argument, a default iterator
times(n, iterator) Invoke its iterator n times, passing the index to it
uniqueId([preïŹx]) Creates a unique id, good for labelling DOM elements
escape(string) Converts & < > " ' / in string to HTML entities (& < ⊠)
template(string, [context]) Converts the string into a template function, using a <% ⊠%> syntax
mixin(object) Adds new functions to _ and to the OOP wrapper, for use with _.chain()
67. Twitter Bootstrap
Built by and for nerds
All skill levels
Desktop, tablets ⊠even smartphones and IE
Custom jQuery Plugins
Based on LESS for customizability
74. General Bootstrap Approach
Basic, semantic, markup
Reasonable default look
Simple CSS classes: "row", "span3", "offset1"
Additiive: more CSS classes to tune
75. Tables
.container
table.span12
caption Bare Table
thead:tr
th.span8 Column A
th Column B
th.span2 Column C
tbody
each row in [1, 2, 3, 4]
tr
each cell in ["A", "B", "C"]
td Cell #{row}-#{cell}
86. Modal Dialogs
ex8.jade
.container
button#danger.btn.btn-danger(data-toggle="modal"
data-target=".x-danger-alert") Do Not Press
.modal.x-danger-alert.fade
.modal-header
a.close(data-dismiss="modal") ×
h3 Why did you press it?
.modal-body
p You pressed the button marked
strong Do Not Press
.
.modal-footer
button.btn.btn-warning(data-dismiss="modal") Continue
button.btn(data-dismiss="modal") Cancel
90. Underscore
Effective, functional JavaScript
Bootstrap
Sharp L&F out of the box
Very customizable
Bootstrap JS
Lots of UI pizzaz, effortlessly
CoffeeScript
Concise, readable JavaScript