Underscore and Backbone Models

546 views

Published on

Presentation given by Allen Cook (@pyromanfo) Jan 23 at the Kentucky JavaScript Users Group meeting discussing the Underscore and Backbone JavaScript libraries.

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
546
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
3
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Underscore and Backbone Models

  1. 1. Underscore & Backbone
  2. 2. Underscore Underscore is a utility belt for Javascript
  3. 3. Supports Functional ProgrammingAccessed as the _ object _.is_NaN(...) _.extend(...) _.each(...)Uses standard Javascript objects
  4. 4. Better Tests● _.isNaN() - returns false with undefined● _.isEqual() - full deep-compare, very efficient● Standard form - _.isFunction, _. isString, _.isUndefined.
  5. 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. 6. bind and bindAllbind makes this useful again_.bind(function, context, [*args])Returns a function that has a consistent thiscontext._.bindAll(object) will bind all objectsproperties with object as the context
  7. 7. Chain, Tap and Value_.chain(value) returns a wrapped value,which will stay wrapped until _.value() iscalled_([42, 43]).chain() .first() // 42 .take(function(val) { return val * 2 }) // 42 * 2 .value() // 84_.tap() lets you temporarily unwrap the valueinside the chain
  8. 8. So Much More● Safer keys, values, lastIndexOf, hasOwnProperty● Array math (union, difference, sorting)● Lightweight Templating● All Under 4kb
  9. 9. Backbone ModelsBackbone Models hold JSON data, typicallyfetched from an external REST APIBackbone Models are defined withUnderscores extend methodBackbone.Model.extend({... model definition ...});
  10. 10. DefaultsBackbone Models can define defaults which italso borrows from Underscorevar Meal = Backbone.Model.extend({ defaults: { "appetizer": "caesar salad", "entree": "ravioli", "dessert": "cheesecake" }});
  11. 11. fetch/saveCalling fetch() on a Backbone Model isanalogous to a "GET" of that resource.Calling save() is analogous to a "PUT"model.fetch();// make changes to model datamodel.save();
  12. 12. Backbone.syncAll I/O on Backbone Models is done withBackbone.syncBy default, Backbone.sync implements itsCRUD methods on an AJAX backend.There exist alternate implementations, such asbackbone.localStorage and backbone.mongodbOr you can write your own ...

×