Spine and BackboneScott Ryan & Jordan McCullough
CoffeeScript✤   Compiling JavaScript✤   Why to consider using it✤   The extra steps involved✤   Relevance to Spine JS
Spine & CoffeeScript✤   Implementations in either JS or CS✤   Benefits of CoffeeScript    ✤   Fewer lines of code    ✤   Cl...
MVC✤   Not a fit for all scenarios✤   Centralized control like for security✤   Ease of update between model and views✤   Se...
Javascript MVC✤   Good Scenario    ✤   Two way data retrieval and storage    ✤   User Interaction and state persistence✤  ...
Single Page Applications✤   Quintessential example: Gmail.com✤   No page refresh✤   Data exchanged by Ajax calls✤   Prime ...
Benefits                                          Spine
JS✤   Provides MVC-like structure✤   Excellent for small, structur...
The Big Picture                                   Spine
JS✤   No other JavaScript libraries needed✤   Simpler implementati...
M Model             Model             Collection                          Backbone                           Objects  C   ...
Structure                                  Spine
JS                 M                            •Storage Spine Class     ...
Class✤   Uses constructors and prototypes and new✤   Backbone.Model.extend(instance props, [class props])✤   Can extend to...
Class                                                Spine
JS✤   All components inherit from Spine Class✤   Provides proto...
Class Proxying                                           Spine
JS✤   Ensure context is maintained✤   Common need with use ...
Class Proxying                     Spine
JS✤   this.proxy( functionCall() )✤   this.proxyAll(functionName)✤   proxied: [fu...
M Model✤   Extends Backbone.Model✤   Constructor args, defaults and initialize function✤   Has a loose lifecycle (CRUD, fe...
M Model✤   url uses id to define server location✤   Can define custom url or urlRoot✤   clone is supported✤   isNew (is id s...
M Modelvar Note = Backbone.Model.extend({             defaults: {                 "type": "public"             }          ...
Model                                                Spine
JS✤   Inherits from Spine’s Class module✤   Establishes agnosti...
Model                                                   Spine
JS✤   Define a Model by assigning class and instance properti...
Model                                               Spine
JS✤   Stores on records property of Model✤   Persist records via...
Model Creation                            Spine
JS                                   Model Namevar Task = Spine.Model.setu...
Model Creation                    Spine
JSTask.extend(Spine.Model.Local);
Model Creation                                Spine
JSTask.include({      validate: function(){          if (!this.name)  ...
Model Persistence                                        Spine
JS✤   Simple as calling save() on model instance✤   Perform...
Model Instance                        Spine
JSvar newRecord = Task.init(     { name: “Learn CoffeeScript” });newRecord.sav...
Model Instance                              Spine
JS                                      Shortcut on Models              ...
M Collection✤   Backbone.Collection✤   Ordered set of model objects✤   Constructor and initialize are run on creation✤   M...
M Collection✤   Backbone includes the underscore library✤   add, remove, and create to impact model items✤   get, getByCid...
M Collectionvar Library = Backbone.Collection.extend({  model: Book});var myLibrary = new Library([  {title: "War and Peac...
C View✤   Extends Backbone.View✤   Integration between Model and view (Controller)✤   View contains an el (element attribu...
C View✤   Render controls the rendering operation bind to change event    ✤   Any method or template library can be used  ...
Controller                                              Spine
JS✤   Inherits from Spine Class✤   Call create() to instanti...
Controller Creation                      Spine
JS var Tasks = Spine.Controller.create({        init: function(){},        ...
Controller Elements                                 Spine
JS✤   elements: {} property    ✤   Improves ease of accessing DO...
Controller Creation                             Spine
JS                             Selector elements: {     "input[type=...
Controller Elements                                     Spine
JS✤   events: {} property    ✤   Scoped within the controlle...
Controller Creation                          Spine
JS                        Event          Selector events: {     "submit...
Controller Elements                                   Spine
JS✤   proxied: {} property    ✤   ensures execution within con...
Controller Creation                        Spine
JS                 Array of function names proxied: ["render", "remove"]
Controller Validation                          Spine
JS  • Handling model validation failure in Controller event    if ( i...
Controller Instantiation Spine
JS                            Sets the context for the selectors and event                 ...
Events✤   Standard and custom with args✤   Mixed into any object (model, collection, etc)✤   bind, unbind, trigger✤   Can ...
Router✤   Backbone.Router.extend(inst, class)✤   Leverages Backbone.History✤   Provides ability to save or define a hashed ...
Router✤   Routes can be predefined✤   route(route, name, callback)    ✤   route can be url or regex    ✤   name is an event...
History✤   Handles hashs for ajax calls    ✤   Supports new pushState and older hash tags✤   pushstate is not used by defa...
Sync✤   Used to sync the server model and client model✤   Defaults to jquery or zepto to make rest calls✤   Can provide cu...
Sync✤   Methods    ✤   create = POST    ✤   read = GET    ✤   update = PUT    ✤   delete = DELETE
Questions?
Get in touch...Scott Ryan                       Jordan McCulloughTwitter: @scryan7371             Twitter: @ambientphotoEm...
References✤   Spine JS    http://maccman.github.com/spine/✤   Spine Todo Example    https://github.com/maccman/spine.todos...
References✤   jQuery Templates    http://api.jquery.com/category/plugins/templates/✤   Handlebars    http://www.handlebars...
Upcoming SlideShare
Loading in …5
×

Spine.js and Backbone.js

12,149 views

Published on

Joint presentation with Jordan McCollough on Spine and Backbone at the Denver HTML5 Users Group

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

No Downloads
Views
Total views
12,149
On SlideShare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
170
Comments
0
Likes
26
Embeds 0
No embeds

No notes for slide
  • \n
  • The first item is the real kicker. Compiling to JavaScript? It’s a scripting language--I shouldn’t have to be compiling this!\n\nIt truly cleans up the number of lines of code and presents an even more readable code than the tidies JavaScript.\n\nThere are extra steps involved, especially for larger projects like we’ll be discussing. Compiling from JavaScript does mean getting a build script involved and adding one or more components (to the CI typically).\n\nCompiled CoffeeScript is pretty printed, so compressing will be another step.\n\nRelevant to Spine JS as Spine JS source was recently rewritten in CoffeeScript.\n
  • \n
  • \n
  • \n
  • Find out how changes on model (delete) affect other controls and how they react\n\n(JORDAN’s slide)\n
  • 1) “Like” in the sense the “V” view is not a component or aspect of the actual Framework.\n\n2) Spine is still a young framework (released in March 2011), but has been out long enough, and tried out amply for simple projects.\n\n3) The “less than 500” lines of framework code permits easy review of the inner workings, allowing insight and understanding.\n
  • 1) Spine comes with everything you need. Unless you’re capitalizing on jQuery to do some heavy lifting and DOM manipulation.\n\n2) Simpler as there are only truly only two core pieces to code to stand up the framework for your SPA.\n\n3) The model library comes with HTML5 Local Storage. No “rolling your own” to hop on the bandwagon.\n\n4) Expectedly, only one JS import needed.\n
  • \n
  • Slightly different than the naming convention and MVC pattern of Backbone...\n\nThe model is DOM and controller agnostic. It simply and solely represents the data.\n\nThe controller handles user interaction (events), DOM manipulation (resulting in a view update) and proxying function calls within the proper context.\n
  • \n
  • Diving right into Spine JS, all “modules” of the framework inherit and are based around the class properties of the Spine JS Class.\n\nAs of recent, Spine has abandoned the Ecmascript 5 object.create for dynamic inheritance in favor of static inheritance obtained from CoffeeScript “class”\n\n\n
  • One of the handy things in the Class of Spine is the built in proxying. \n\nThis ensures context is maintained within the class when callbacks and event binding could otherwise get context all tangled up.\n\nWhile similar support is present in Backbone, the implementation is a bit more redundant, whereas Spine has taken a lighter, one time assignment approach.\n
  • Let’s see some of the ways to setup or utilize Spine’s proxy for function calls\n
  • \n
  • \n
  • \n
  • As noted, all modules inherit from Class, as does Model.\n\nThere should be no DOM or controller coupling in the Model. While there are means of going astray and falling to this, be aware that models should be fully decoupled.\n\n
  • The “create” function name is already reserved within the model, therefore defining a model is used on the Spine.Model.setup call.\n
  • So let’s see what we’ll be doing with a Model\n1) Models contain a hash “records”. This is equivalent to a basic collection in Backbone.\n2) Persistence can be easily implemented by extending Spine local or ajax\n3) Validation on model properties is built into the model as an instance property\n4) Your own helper functions can also easily be rolled in as class properties by directly assigning them onto the Model\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Spine.js and Backbone.js

    1. 1. Spine and BackboneScott Ryan & Jordan McCullough
    2. 2. CoffeeScript✤ Compiling JavaScript✤ Why to consider using it✤ The extra steps involved✤ Relevance to Spine JS
    3. 3. Spine & CoffeeScript✤ Implementations in either JS or CS✤ Benefits of CoffeeScript ✤ Fewer lines of code ✤ Cleaner syntax ✤ Less namespace pollution ✤ All Spine examples now in CoffeeScript
    4. 4. MVC✤ Not a fit for all scenarios✤ Centralized control like for security✤ Ease of update between model and views✤ Separate DOM from Data✤ Easy to add custom Events✤ More like M-C with any V
    5. 5. Javascript MVC✤ Good Scenario ✤ Two way data retrieval and storage ✤ User Interaction and state persistence✤ Poor Scenario ✤ Uni directional data consumption ✤ Simple web sites
    6. 6. Single Page Applications✤ Quintessential example: Gmail.com✤ No page refresh✤ Data exchanged by Ajax calls✤ Prime situation for JavaScript MVC
    7. 7. Benefits Spine
JS✤ Provides MVC-like structure✤ Excellent for small, structured SPAs✤ Small codebase, easy to examine and inspect
    8. 8. The Big Picture Spine
JS✤ No other JavaScript libraries needed✤ Simpler implementation than other JS-MVC frameworks✤ Comes pre-packaged with HTML5 goodies “out of the box”✤ Only a single import of spine.js
    9. 9. M Model Model Collection Backbone Objects C Events ViewController Router V View History Sync
    10. 10. Structure Spine
JS M •Storage Spine Class •Local Model •Persistence •Ajax •Validation C V •Event Handling •Event Binding Controller View •DOM Changes •Proxying
    11. 11. Class✤ Uses constructors and prototypes and new✤ Backbone.Model.extend(instance props, [class props])✤ Can extend to any depth✤ Overhead in copying✤ Super is done via the prototype (Limited scope)
    12. 12. Class Spine
JS✤ All components inherit from Spine Class✤ Provides prototypical inheritance✤ Dynamic inheritance means property resolution at runtime✤ Does not use new keyword✤ Does not use constructors in the typical sense
    13. 13. Class Proxying Spine
JS✤ Ensure context is maintained✤ Common need with use of callbacks✤ Inherited from core Spine Class✤ Ensures functions called with class’ local context (Backbone relies on parameter on each bind call)
    14. 14. Class Proxying Spine
JS✤ this.proxy( functionCall() )✤ this.proxyAll(functionName)✤ proxied: [functionName]
    15. 15. M Model✤ Extends Backbone.Model✤ Constructor args, defaults and initialize function✤ Has a loose lifecycle (CRUD, fetch, save, destroy)✤ id versus cid✤ get, set , has, unset, clear✤ validation is implemented here✤ Called before each set and/or save can return any error type/string
    16. 16. M Model✤ url uses id to define server location✤ Can define custom url or urlRoot✤ clone is supported✤ isNew (is id set or not)✤ change, hasChanged, changedAttributes, previous, previousAttributes
    17. 17. M Modelvar Note = Backbone.Model.extend({ defaults: { "type": "public" } set: function(attributes, options) { Backbone.Model.prototype.set.call(this, attributes, options); ... }, allowedToEdit: function(account) { return true; } });var PrivateNote = Note.extend({ allowedToEdit: function(account) { return account.owns(this); } });window.scottNote = new PrivateNote;
    18. 18. Model Spine
JS✤ Inherits from Spine’s Class module✤ Establishes agnostic data model✤ Used to strictly store & manipulate data✤ Entirely de-coupled from any other component (controller)
    19. 19. Model Spine
JS✤ Define a Model by assigning class and instance properties✤ Instantiate a model by calling setup()✤ Utilize Class extend and include for class and instance properties✤ A word of caution for instantiation and function call
    20. 20. Model Spine
JS✤ Stores on records property of Model✤ Persist records via Local Storage or Ajax (Inherited from Spine.Model.Local and Spine.Model.Ajax)✤ Validates properties (instance properties)
    21. 21. Model Creation Spine
JS Model Namevar Task = Spine.Model.setup("Task", ["name", "done"]); Model Attributes
    22. 22. Model Creation Spine
JSTask.extend(Spine.Model.Local);
    23. 23. Model Creation Spine
JSTask.include({ validate: function(){ if (!this.name) return "A task name is required"; }});
    24. 24. Model Persistence Spine
JS✤ Simple as calling save() on model instance✤ Performs persistence based on extended class of Spine.Model.Local or Spine.Model.Ajax✤ Shortcut function for init-ing and saving a record
    25. 25. Model Instance Spine
JSvar newRecord = Task.init( { name: “Learn CoffeeScript” });newRecord.save();
    26. 26. Model Instance Spine
JS Shortcut on Models 1) Inits a new record with properties ofvar newRecord = Task.create( passed in object literal { name: “Learn CoffeeScript” } 2) Persists by calling save());
    27. 27. M Collection✤ Backbone.Collection✤ Ordered set of model objects✤ Constructor and initialize are run on creation✤ Model is set via a property and list can be passed on creation✤ Add and remove trigger change events✤ Model events also trigger in collection as well
    28. 28. M Collection✤ Backbone includes the underscore library✤ add, remove, and create to impact model items✤ get, getByCid, at, length, sort✤ Custom sorting via comparator✤ pluck returns a property from each member✤ fetch, reset (multi model update)✤ url can be customized
    29. 29. M Collectionvar Library = Backbone.Collection.extend({ model: Book});var myLibrary = new Library([ {title: "War and Peace", author: “Leo Tolstoy”}, {title: "Dogs for Dummies", author: “Gina Spadafori”}, {title: "Spring in Action", author: “Craig Walls”}]);
    30. 30. C View✤ Extends Backbone.View✤ Integration between Model and view (Controller)✤ View contains an el (element attribute)✤ Bound to view with selection by tagname, id, classname✤ Bound to model or collection on creation✤ Constructor and initialize is run on creation
    31. 31. C View✤ Render controls the rendering operation bind to change event ✤ Any method or template library can be used ✤ return this at end to allow chaining✤ make and remove to control creation and removal from the DOM✤ Event delegation is supported and preferred
    32. 32. Controller Spine
JS✤ Inherits from Spine Class✤ Call create() to instantiate a controller✤ Utilize Class extend and include for class and instance properties✤ Integral to tying Model & View together (the “glue”)
    33. 33. Controller Creation Spine
JS var Tasks = Spine.Controller.create({ init: function(){}, elements: {}, events:{}, proxied:{} });
    34. 34. Controller Elements Spine
JS✤ elements: {} property ✤ Improves ease of accessing DOM elements without repeated selector calls ✤ Allows developer to give “friendly” names to DOM elements defined in view/HTML
    35. 35. Controller Creation Spine
JS Selector elements: { "input[type=text]": "input", ".item": "wrapper" Friendly Name } Accessible within controller by this.input
    36. 36. Controller Elements Spine
JS✤ events: {} property ✤ Scoped within the controller’s el property associated element ✤ Optional selector of child element for event binding
    37. 37. Controller Creation Spine
JS Event Selector events: { "submit form": "create", "click .clear": "clear" Event Callback }
    38. 38. Controller Elements Spine
JS✤ proxied: {} property ✤ ensures execution within controller context ✤ One-time assignment
    39. 39. Controller Creation Spine
JS Array of function names proxied: ["render", "remove"]
    40. 40. Controller Validation Spine
JS • Handling model validation failure in Controller event if ( item.save() ) { // Proceed //Validation or persistence failed } else { var msg = item.validate(); alert(msg); }
    41. 41. Controller Instantiation Spine
JS Sets the context for the selectors and event binding of elements within context of controller var view = Tasks.init({item: task});
    42. 42. Events✤ Standard and custom with args✤ Mixed into any object (model, collection, etc)✤ bind, unbind, trigger✤ Can use namespaces and/or ‘all’✤ Can include execution context✤ object.bind(‘note:myevent’, callback, this)✤ silent changes are supported
    43. 43. Router✤ Backbone.Router.extend(inst, class)✤ Leverages Backbone.History✤ Provides ability to save or define a hashed location✤ route(route, name, callback) ✤ route can be url or regex ✤ name is an event that is trigger on routing
    44. 44. Router✤ Routes can be predefined✤ route(route, name, callback) ✤ route can be url or regex ✤ name is an event that is triggered on routing✤ navigate will save a url
    45. 45. History✤ Handles hashs for ajax calls ✤ Supports new pushState and older hash tags✤ pushstate is not used by default✤ Used if you use routers✤ Call start after all routers are set up
    46. 46. Sync✤ Used to sync the server model and client model✤ Defaults to jquery or zepto to make rest calls✤ Can provide custom implementation✤ Backbone.sync(model, method, options)✤ options ✤ jquery success, error callbacks, etc
    47. 47. Sync✤ Methods ✤ create = POST ✤ read = GET ✤ update = PUT ✤ delete = DELETE
    48. 48. Questions?
    49. 49. Get in touch...Scott Ryan Jordan McCulloughTwitter: @scryan7371 Twitter: @ambientphotoEmail: scott@theryansplace.com Email: jordanm@ambientideas.comPhone: 303-263-3044 Phone: 720-249-2766Web: soaringeagleco.com Web: ambientideas.com
    50. 50. References✤ Spine JS http://maccman.github.com/spine/✤ Spine Todo Example https://github.com/maccman/spine.todos✤ CoffeeScript http://jashkenas.github.com/coffee-script/✤ Addy Osmani’s Building JS Web Apps with MVC & Spine.js http://addyosmani.com/blog/building-apps-spinejs/
    51. 51. References✤ jQuery Templates http://api.jquery.com/category/plugins/templates/✤ Handlebars http://www.handlebarsjs.com/

    ×