Backbone.jsWhat it is, what it does, and why we use it at Usable.
Backbone.js• Not a magic bullet.• Not tiny once you make it useful (139kb).• Not perfect, some things are hard.• Not suita...
Backbone.js• MVC - Model,View, Controller• (Backbone.js calls the controller a Router)• Collections, Sync, History, and mo...
Backbone.jsModels - Objects that represent a thing. • Models are objects • Core of Backbone.js • Contains an array of attr...
Backbone.jsModels - Objects that represent a thing.var Cat = Backbone.Model.extend({      defaults: {           name: ‘Cat...
Backbone.jsUsing a model - Getting attributes.var Purrkins = new Cat({    name: ‘Purrkins’,});console.log(Purrkins.get(“br...
Backbone.jsUsing a model - Setting attributes.Purrkins.set({name:‘Mister Purrkins’, age: 6});console.log(Purrkins.get(“nam...
Backbone.jsUsing a model - Saving. • Saving a model is easy • Backbone Sync • Restful interface - GET, POST, PUT, DELETE •...
Backbone.jsUsing a model - Saving to an API.var Cat = Backbone.Model.extend({      url: ‘/api/cat/’,      defaults: {     ...
Backbone.jsUsing a model - Saving to an API.Purrkins.save({name:‘Mister Purrkins’, age: 6});POST http://localhost/api/cat/...
Backbone.jsUsing a model - Validating. • Should you just save everything? • Models need to be validated • No helper functi...
Backbone.jsUsing a model - Validating before saving.var Cat = Backbone.Model.extend({      url: ‘/api/cat/’,      defaults...
Backbone.jsUsing a model - Validating before saving.Purrkins.save(    {age: 6},    success: function(){ console.log(‘Kitty...
Backbone.jsUsing a model - API errors.Purrkins.save(    {age: 4},    success: function(){ console.log(‘Kitty saved’); },  ...
Backbone.jsCollections - Groups of objects. • Collections are ‘arrays’ of models • Add, push, shift, pop, unshift, etc • B...
Backbone.jsCollections - Groups of objects.var Glaring = Backbone.Collection.extend({      model: Cat});Collective noun fo...
Backbone.jsUsing a collection - Adding models.var CrazyCatLady = new Glaring([    {id: 1, name: ‘Purrkins’, legs: 3},    {...
Backbone.jsUsing a collection - Underscore.js rocks.var TabbyCats = CrazyCatLady.where({colour: “Tabby”);console.log(Tabby...
Backbone.jsViews - Displaying a model. • Views are not HTML • Views are a description of a model • The HTML code comes fro...
Backbone.jsViews - Displaying a model.var Catview = Backbone.View.extend({      initialize: function() {         _.bindAll...
Backbone.jsViews - Displaying a collection. • Collections can have views • Actually a view containing views • Nested? Sort...
Backbone.jsViews - Displaying a collection.var CatRowView = Backbone.View.extend({  tagName:     "div",  initialize: funct...
Backbone.jsViews - Displaying a collection.var CatListView = Backbone.View.extend({  initialize: function(data) {       th...
Backbone.jsViews - Displaying a collection.var catslisting = new CatListView({collection: CrazyCatLady});CatListView   Cat...
Backbone.jsViews - Binding events. • Views are not just about displaying things • Binding events to View elements • Stuff ...
Backbone.jsViews - Binding events.var Catview = Backbone.View.extend({      initialize: function() {         _.bindAll( th...
Backbone.jsRouting - Backbone.js’ controller.var Router = Backbone.Router.extend({      routes: {           “/cats”: “cats...
Backbone.jsRouting - Backbone.js’ controller. cats: function(){     var catlisting = new CatList({ collection: CrazyCatLad...
Backbone.jsHistory - Handling hashchange eventsBackbone.history.start();Important notes:• Must start after the router obje...
Backbone.jsWho’s using it? • UsableHQ (that’s me!) • Foursquare, Stripe, DocumentCloud • LinkedIn, Basecamp, AirBnB (for m...
“Don’t let the perfect be the enemy of the good.”                                             Voltaire
Chris NealeTechnical Director, UsableHQ    chris@usablehq.com        @usablehq      or @onion2k
Upcoming SlideShare
Loading in...5
×

Backbone.js

4,151

Published on

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

No Downloads
Views
Total Views
4,151
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
162
Comments
0
Likes
5
Embeds 0
No embeds

No notes for slide
  • \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
  • Backbone.js

    1. 1. Backbone.jsWhat it is, what it does, and why we use it at Usable.
    2. 2. Backbone.js• Not a magic bullet.• Not tiny once you make it useful (139kb).• Not perfect, some things are hard.• Not suitable for some applications.
    3. 3. Backbone.js• MVC - Model,View, Controller• (Backbone.js calls the controller a Router)• Collections, Sync, History, and more• Underscore.js, json2.js, jQuery (or Zepto)
    4. 4. Backbone.jsModels - Objects that represent a thing. • Models are objects • Core of Backbone.js • Contains an array of attributes • Listens for events
    5. 5. Backbone.jsModels - Objects that represent a thing.var Cat = Backbone.Model.extend({ defaults: { name: ‘Cat’, breed: Moggy, colour: ‘Ginger’, legs: 4 }, initialize: function(data) { },});
    6. 6. Backbone.jsUsing a model - Getting attributes.var Purrkins = new Cat({ name: ‘Purrkins’,});console.log(Purrkins.get(“breed”)); //Moggyconsole.log(Purrkins.get(“colour”)); //Gingerconsole.log(Purrkins.get(“name”)); //Purrkins
    7. 7. Backbone.jsUsing a model - Setting attributes.Purrkins.set({name:‘Mister Purrkins’, age: 6});console.log(Purrkins.get(“name”)); //Mister Purrkins
    8. 8. Backbone.jsUsing a model - Saving. • Saving a model is easy • Backbone Sync • Restful interface - GET, POST, PUT, DELETE • Up to you to write the server side stuff
    9. 9. Backbone.jsUsing a model - Saving to an API.var Cat = Backbone.Model.extend({ url: ‘/api/cat/’, defaults: { name: ‘Cat’, breed: Moggy, colour: ‘Ginger’, legs: 4 }, initialize: function(data) { },});
    10. 10. Backbone.jsUsing a model - Saving to an API.Purrkins.save({name:‘Mister Purrkins’, age: 6});POST http://localhost/api/cat/PAYLOAD: { "name":"Mister Purrkins", "breed":"Moggy", "colour":"Ginger", "legs":4, “age”: 6}
    11. 11. Backbone.jsUsing a model - Validating. • Should you just save everything? • Models need to be validated • No helper functions for validation • Underscore.js provides some
    12. 12. Backbone.jsUsing a model - Validating before saving.var Cat = Backbone.Model.extend({ url: ‘/api/cat/’, defaults: { name: ‘Cat’, breed: Moggy, colour: ‘Ginger’, legs: 4 }, initialize: function(data) { }, validate: function(attrs) { var errors = {}; if (attrs.age < 5) { errors.age = ‘Must be below 5’; } if (!_.isEmpty(errors)) { errors.invalid = true; return errors; } },});
    13. 13. Backbone.jsUsing a model - Validating before saving.Purrkins.save( {age: 6}, success: function(){ console.log(‘Kitty saved’); }, error: function(model,error){ if (error.invalid==true) { $.each(_.keys(error), function(i,el){ console.log(el+”:”+error[el]); }); } else { console.log(“Error status: ”+error.status); console.log(“Error response: ”+error.responseText); } });age:Must be below 5
    14. 14. Backbone.jsUsing a model - API errors.Purrkins.save( {age: 4}, success: function(){ console.log(‘Kitty saved’); }, error: function(model,error){ if (error.invalid==true) { $.each(_.keys(error), function(i,el){ console.log(el+”:”+error[el]); }); } else { console.log(“Error status: ”+error.status); console.log(“Error response: ”+error.responseText); } });Error status: 500Error response: Internal Server Error - Database not found
    15. 15. Backbone.jsCollections - Groups of objects. • Collections are ‘arrays’ of models • Add, push, shift, pop, unshift, etc • Built on Underscore.js • Filter, sort, etc
    16. 16. Backbone.jsCollections - Groups of objects.var Glaring = Backbone.Collection.extend({ model: Cat});Collective noun for a group of cats: a glaring
    17. 17. Backbone.jsUsing a collection - Adding models.var CrazyCatLady = new Glaring([ {id: 1, name: ‘Purrkins’, legs: 3}, {id: 2, name: ‘Napoleon’, colour:‘Tabby’}, {id: 3, name: ‘Josey’, colour:‘Tabby’, legs: 100}, {id: 4, name: ‘Coco’, breed:‘Siamese’, colour:‘Chocolate’}, {id: 5, name: ‘Charlie’},]);console.log(CrazyCatLady.get(2).get(“name”)); //NapoleonCrazyCatLady.add({id: 6, name: ‘Augustus’});console.log(CrazyCatLady.get(6).get(“name”)); //Augustus
    18. 18. Backbone.jsUsing a collection - Underscore.js rocks.var TabbyCats = CrazyCatLady.where({colour: “Tabby”);console.log(TabbyCats); //Napoleon, Joseyvar fourorfivelegs = CrazyCatLady.filter(function(Cat){ var legs = cat.get(“legs”); return (legs > 3 && legs < 6);});console.log(fourorfivelegs); //Napoleon, Coco, Charlie, Augustusvar names = CrazyCatLady.pluck(“name”);console.log(names); //Purrkins, Napoleon, Josey, Coco, Charlie, Augustus
    19. 19. Backbone.jsViews - Displaying a model. • Views are not HTML • Views are a description of a model • The HTML code comes from templates • Works with any template system
    20. 20. Backbone.jsViews - Displaying a model.var Catview = Backbone.View.extend({ initialize: function() { _.bindAll( this, render ) }, render: function() { this.$el.html(templates.catview(this.model.toJSON())); return this; },});var c = new Catview({model: CrazyCatLady.get(1) });$(‘div#cat’).html(c.render().el);
    21. 21. Backbone.jsViews - Displaying a collection. • Collections can have views • Actually a view containing views • Nested? Sort of. • Think in terms of partials/blocks
    22. 22. Backbone.jsViews - Displaying a collection.var CatRowView = Backbone.View.extend({ tagName: "div", initialize: function() { _.bindAll( this, render ) this.model.bind(change, this.render, this); }, render: function() { this.$el.html(templates.catrowview(this.model.toJSON())); return this; },});
    23. 23. Backbone.jsViews - Displaying a collection.var CatListView = Backbone.View.extend({ initialize: function(data) { this.collection = data.collection; this.collection.bind(add, this.addOne, this); this.collection.bind(all, this.render, this); this.collection.each(this.addOne); }, render: function() { }, addOne: function(cat) { var view = new CatRowView({model:cat}); $("div#cats").append(view.render().el); },});
    24. 24. Backbone.jsViews - Displaying a collection.var catslisting = new CatListView({collection: CrazyCatLady});CatListView CatRowView - Purrkins CatRowView - Napoleon CatRowView - Josey CatRowView - Coco CatRowView - Charlie CatRowView - Augustus
    25. 25. Backbone.jsViews - Binding events. • Views are not just about displaying things • Binding events to View elements • Stuff happens when you click things • Or double click, press a key, whatever
    26. 26. Backbone.jsViews - Binding events.var Catview = Backbone.View.extend({ initialize: function() { _.bindAll( this, render ) }, events: { "click a.edit": "edit", }, render: function() { this.$el.html(templates.catview(this.model.toJSON())); return this; }, edit: function(){ app.navigate(#/cats/+this.model.id, true); }});
    27. 27. Backbone.jsRouting - Backbone.js’ controller.var Router = Backbone.Router.extend({ routes: { “/cats”: “cats”, “/cats/:catid”: “catview”, “*path”: “default”, }, cats: function(){ //Something to do with cats }, catview: function(catid){ //Something to do with a specific cat }, default: function(path){ //Everything else }});
    28. 28. Backbone.jsRouting - Backbone.js’ controller. cats: function(){ var catlisting = new CatList({ collection: CrazyCatLady }); $(div#content).html(catlisting.render().el); }, catview: function(id){ var catview = new CatView({ model: CrazyCatLady.get(id) }); $(div#content).html(catview.render().el); }, default: function(path){ var template = path.substr(1); //strip the initial / if (template==) { template = base; } ui.display(path, template); },
    29. 29. Backbone.jsHistory - Handling hashchange eventsBackbone.history.start();Important notes:• Must start after the router object.• Must start after the HTML is done. Wrap it inyour favourite flavour of jQuery.ready();• If you can get pushState to work, tell me how.
    30. 30. Backbone.jsWho’s using it? • UsableHQ (that’s me!) • Foursquare, Stripe, DocumentCloud • LinkedIn, Basecamp, AirBnB (for mobile) • Flow, Wunderkit, Khan Academy
    31. 31. “Don’t let the perfect be the enemy of the good.” Voltaire
    32. 32. Chris NealeTechnical Director, UsableHQ chris@usablehq.com @usablehq or @onion2k
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×