• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Spine.js and Backbone.js
 

Spine.js and Backbone.js

on

  • 11,599 views

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

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

Statistics

Views

Total Views
11,599
Views on SlideShare
11,598
Embed Views
1

Actions

Likes
26
Downloads
164
Comments
0

1 Embed 1

http://a0.twimg.com 1

Accessibility

Categories

Upload Details

Uploaded via as Apple Keynote

Usage Rights

CC Attribution-ShareAlike LicenseCC Attribution-ShareAlike License

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • \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 Spine.js and Backbone.js Presentation Transcript

  • 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 ✤ Cleaner syntax ✤ Less namespace pollution ✤ All Spine examples now in CoffeeScript
  • 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
  • Javascript MVC✤ Good Scenario ✤ Two way data retrieval and storage ✤ User Interaction and state persistence✤ Poor Scenario ✤ Uni directional data consumption ✤ Simple web sites
  • Single Page Applications✤ Quintessential example: Gmail.com✤ No page refresh✤ Data exchanged by Ajax calls✤ Prime situation for JavaScript MVC
  • Benefits Spine
JS✤ Provides MVC-like structure✤ Excellent for small, structured SPAs✤ Small codebase, easy to examine and inspect
  • 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
  • M Model Model Collection Backbone Objects C Events ViewController Router V View History Sync
  • Structure Spine
JS M •Storage Spine Class •Local Model •Persistence •Ajax •Validation C V •Event Handling •Event Binding Controller View •DOM Changes •Proxying
  • 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)
  • 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
  • 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)
  • Class Proxying Spine
JS✤ this.proxy( functionCall() )✤ this.proxyAll(functionName)✤ proxied: [functionName]
  • 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
  • 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
  • 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;
  • 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)
  • 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
  • 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)
  • Model Creation Spine
JS Model Namevar Task = Spine.Model.setup("Task", ["name", "done"]); Model Attributes
  • Model Creation Spine
JSTask.extend(Spine.Model.Local);
  • Model Creation Spine
JSTask.include({ validate: function(){ if (!this.name) return "A task name is required"; }});
  • 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
  • Model Instance Spine
JSvar newRecord = Task.init( { name: “Learn CoffeeScript” });newRecord.save();
  • 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());
  • 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
  • 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
  • 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”}]);
  • 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
  • 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
  • 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”)
  • Controller Creation Spine
JS var Tasks = Spine.Controller.create({ init: function(){}, elements: {}, events:{}, proxied:{} });
  • 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
  • Controller Creation Spine
JS Selector elements: { "input[type=text]": "input", ".item": "wrapper" Friendly Name } Accessible within controller by this.input
  • Controller Elements Spine
JS✤ events: {} property ✤ Scoped within the controller’s el property associated element ✤ Optional selector of child element for event binding
  • Controller Creation Spine
JS Event Selector events: { "submit form": "create", "click .clear": "clear" Event Callback }
  • Controller Elements Spine
JS✤ proxied: {} property ✤ ensures execution within controller context ✤ One-time assignment
  • Controller Creation Spine
JS Array of function names proxied: ["render", "remove"]
  • 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); }
  • 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});
  • 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
  • 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
  • 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
  • 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
  • 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
  • Sync✤ Methods ✤ create = POST ✤ read = GET ✤ update = PUT ✤ delete = DELETE
  • Questions?
  • 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
  • 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/
  • References✤ jQuery Templates http://api.jquery.com/category/plugins/templates/✤ Handlebars http://www.handlebarsjs.com/