Presentation given by Allen Cook (@pyromanfo) Jan 23 at the Kentucky JavaScript Users Group meeting discussing the Underscore and Backbone JavaScript libraries.
4. Better Tests
● _.isNaN() - returns false with undefined
● _.isEqual() - full deep-compare, very
efficient
● Standard form - _.isFunction, _.
isString, _.isUndefined.
5. Extend for Mixins
_.extend(object, mixins)
● Works on any Javascript object
● Mixins are just standard JS objects too
{
addon_function: function()....
another_addon: function() ...
}
6. bind and bindAll
bind makes 'this' useful again
_.bind(function, context, [*args])
Returns a function that has a consistent 'this'
context.
_.bindAll(object) will bind all object's
properties with object as the context
7. Chain, Tap and Value
_.chain(value) returns a wrapped value,
which will stay wrapped until _.value() is
called
_([42, 43]).chain()
.first() // 42
.take(function(val) { return val * 2 }) // 42 * 2
.value() // 84
_.tap() let's you temporarily unwrap the value
inside the chain
8. So Much More
● Safer keys, values, lastIndexOf,
hasOwnProperty
● Array math (union, difference, sorting)
● Lightweight Templating
● All Under 4kb
9. Backbone Models
Backbone Models hold JSON data, typically
fetched from an external REST API
Backbone Models are defined with
Underscore's extend method
Backbone.Model.extend({
... model definition ...
});
10. Defaults
Backbone Models can define defaults which it
also borrows from Underscore
var Meal = Backbone.Model.extend({
defaults: {
"appetizer": "caesar salad",
"entree": "ravioli",
"dessert": "cheesecake"
}
});
11. fetch/save
Calling fetch() on a Backbone Model is
analogous to a "GET" of that resource.
Calling save() is analogous to a "PUT"
model.fetch();
// make changes to model data
model.save();
12. Backbone.sync
All I/O on Backbone Models is done with
Backbone.sync
By default, Backbone.sync implements it's
CRUD methods on an AJAX backend.
There exist alternate implementations, such as
backbone.localStorage and backbone.
mongodb
Or you can write your own ...