• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Taming that client side mess with Backbone.js
 

Taming that client side mess with Backbone.js

on

  • 4,296 views

 

Statistics

Views

Total Views
4,296
Views on SlideShare
3,615
Embed Views
681

Actions

Likes
7
Downloads
53
Comments
0

13 Embeds 681

http://elegantcode.com 605
http://feeds.feedburner.com 30
http://jarodferguson.com 18
http://www.linkedin.com 6
http://www.newsblur.com 4
http://www.bonkm.com 4
http://www.netvibes.com 3
http://feeds2.feedburner.com 3
http://dashboard.bloglines.com 2
http://reader.googleusercontent.com 2
https://www.linkedin.com 2
http://nodeslide.herokuapp.com 1
http://feedproxy.google.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

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
  • Thank youQ’s- Who has used Mlibs? (jquery, prototype, mootools)- End to End frameworks? (Knockout, Ember, Spine)-Used backbone?
  • MS Developer Advisory CouncilData Access InsiderIdaho Startup Weekend Winner
  • A tool to know more about your documents, ppl, places and orgs, dates. Annotate, highlight & share (Think publishers)
  • A convention based JavaScript presentation framework. Its small powerful,gives you structure to build on- More than one way to do it (i.e. Respect the boundaries, model should not know about view, but some do it anyway)- Dependencies: underscore, jquery/zeptoThere is a common misconception that it is MVC, but that is inaccurate, which well talk about later.
  • No one really important!DEMO!
  • And down we go! Hope you have enough air….You'll be gone a whileStill not sure why you would you use bb? Lets talk about why
  • Backbone gives us StructureJavascriptis so flexible, it makes it easy to create globs of unorganized code. I am sure most of you have experienced this.Becomes ever important as a project scales
  • Backbone gives us ConventionConvention provides us some Familiarity, esp when working in teams, multiple projects
  • Backbone separates concernsBusiness logic, view markup, data, persistence
  • LightweightOnly 1200 lines of code including comments16kb
  • Why would you use bb?- Building SPA’s or sophisticated users interfaces with plain javascript or jQuery is complicated- Quickly turn into a mess of callbacks tied to DOM elements- You can write your own framework to solve this, but that can be a lot of work. - There are many of these frameworks popping up. (knockout, ember, spine, sproutcore, batman)Lets take a look at the components of backbone
  • Models are the heart of any application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control. You extend Backbone.Model with your domain-specific methods, and Model provides a basic set of functionality for managing changes.
  • Don’t get hung up on the nameBackbone views are almost more convention than they are codethey don't determine anything about your HTML or CSS for you, and can be used with any JavaScript templating library. The general idea is to organize your interface into logical views, backed by models, each of which can be updated independently when the model changes, without having to redraw the page. Instead of digging into a JSON object, looking up an element in the DOM, and updating the HTML by hand, you can bind your view's render function to the model's "change" event — and now everywhere that model data is displayed in the UI, it is always immediately up to date.
  •  Basic view- el, tag, class- Event handlingscoped selector view.$, this.$\\Note render returns this for chaining- Binding model events- models 'change'- bindAll scope (not needed)- 3rd ‘this’ arg, protip
  • Can define in script tags, or in code. Compile for performance
  • Collections are ordered sets of models. You can bind "change" events to be notified when any model in the collection has been modified, listen for "add" and "remove"events, fetch the collection from the server, and use a full suite of Underscore.js methods.
  • Really deserves its own talk“Underscore provides 60-odd functions that support both the usual functional suspects:map, select, invoke — as well as more specialized helpers: function binding, javascripttemplating, deep equality testing, and so on”
  • Using local storage, but could set url & fetch
  • Showing fetch from server
  • Best way to talk about routers, isto just take a look at one.
  • Pretty simple. DEMO!Start history.
  • Events is a module that can be mixed in to any object, giving the object the ability to bind and trigger custom named events. Events do not have to be declared before they are bound, and may take passed arguments.Really easy to decouple objects (models & views) w/ simple pub/subShow WW?
  • Backbone.sync is the function that Backbone calls every time it attempts to read or save a model to the server. By default, it uses (jQuery/Zepto).ajax to make a RESTful JSON request and returns a jqXHR. You can override it in order to use a different persistence strategy, such as WebSockets, XML transport, or Local Storage.DEMO!
  • Here's a list of all of the built-in events that Backbone.js can fire. You're also free to trigger your own events on Models and Views as you see fit.
  • Async Module Definitions – Design to load modular code asynchronously (browser or server)

Taming that client side mess with Backbone.js Taming that client side mess with Backbone.js Presentation Transcript

  • Taming that client side mess with…
  • About mejarod.ferguson@gmail.com @jarodf
  • Backbone.js Oct 2010, DocumentCloud(Underscore.js, CoffeeScript)
  • What does it do?“Backbone.js gives structure to web applicationsby providing models with key-value binding andcustom events, collections with a rich API ofenumerable functions,views with declarativeevent handling, and connects it all to yourexisting API over a RESTful JSON interface.”
  • Who uses backbone?
  • But wait, this is way less code? $(function () { var count = 0; $(#thebutton).click(function () { count++; $("#secondview").html(count); }); });
  • var count = 0;$(#thebutton).click(function () { count++; if (count > 1) { $.ajax({ url: /foo/dizzle/, type: "POST", dataType: json, data: someObjects.toJSON(), success: function (result) { if (result.status == Success) { var html = ; for (d in result.data) { if (d.whatever === ‘yola) { html += "<li class=yep>" + d.name + "</li>"; } else { html += "<li class=nope>" + d.name + "</li>"; } } $("#secondview").html(html); toggleHistItems(result.tabId); } else { alert(result.status); } }, error: function (err) { uhOh(err); } }); } else { yipKiYay(); }});
  • var count = 0;$(#thebutton).click(function () { count++; if (count > 1) { $.ajax({ url: /foo/dizzle/, type: "POST", dataType: json, data: someObjects.toJSON(), success: function (result) { if (result.status == Success) { var html = ; for (d in result.data) { if (d.whatever === ‘yola) { html += "<li class=yep>" + d.name + "</li>"; } else { html += "<li class=nope>" + d.name + "</li>"; } } $("#secondview").html(html); toggleHistItems(result.tabId); } else { alert(result.status); } }, error: function (err) { uhOh(err); } }); } else { yipKiYay(); }});
  • The jQuery DivideRebecca Murphy – JSConf.eu
  • http://www.flickr.com/photos/ppix/2305078608/
  • Problem Not Unique• Avoid callback soup• Patterns > Spaghetti• Logic in expected place, not tied to DOM
  • Model• Thing• Business Logic• Persistence
  • var Todo = Backbone.Model.extend({ defaults: { content: "empty todo...", done: false }, initialize: function() { if (!this.get("content")) { this.set({"content": this.defaults.content}); } }, toggle: function() { this.save({done: !this.get("done")}); }, clear: function() { this.destroy(); }});
  • Common Model Functions/Properties• defaults, initialize• get/set/unset• id/cid• custom functions• validate/isValid• save/fetch/destroy• url/urlRoot
  • Views• Convention tied to a box on the page• Handles presentation logic (Presenter?)• Tied to a Model or Collections• Listens for Model changes• Listens for DOM events (click, hover, etc)
  • var TodoView = Backbone.View.extend({ tagName: "li", template: _.template($(#item-template).html()), events: { "click .check": "toggleDone", "dblclick label.todo-content": "edit", "click span.todo-destroy": "clear", "keypress .todo-input": "updateOnEnter", "blur .todo-input": "close" }, initialize: function () { this.model.bind(change, this.render, this); this.model.bind(destroy, this.remove, this); }, render: function () { $el.html(this.template(this.model.toJSON())); this.input = this.$(.todo-input); return this; }, edit: function () { $el.addClass("editing"); this.input.focus(); }, … snipped ..});
  • Templates• The ‘Markup’• Decouples UI Definition from data logic• Promotes reuse• Increased maintainability• Backbone doesn’t care which one you use – Underscore, Mustache, jsRender, jQuery etc
  • $.each(messages.reverse(), function(index, message) { $(#messageList).append( <li><span class="list-title"> + message.userName + </span> + <abbr class="list-timestamp" title=" + message.datePosted + "></abbr> + <p class="list-text"> + message.messageText + </p></li>); }});
  • <script id="categoryTemplate" type="text/x-jquery-tmpl"> <button class="back-btn pointer" title="Back"></button> <div class="title"> ${name} </div> <ul> {{each(i, item) items}} <li class="hover" iid=${item.id}> <div class="title">${item.name}</div> <div class="desc">${item.description}</div> </li> {{/each}} </ul></script>var fragment = $(#categoryTemplate).tmpl(category);$(this.el).html(fragment);
  • Collections• Set of Models• add, remove, refresh• get, at, length• fetch• sorting• _
  • TV Timeout for Underscore.js• Collections • Functions – each, any, all, find – bind, bindAll – filter/select, map, reduce – memoize, defer• Arrays • Objects – first, last – keys, values – union, intersect – extend, clone findCategory: function(id) { return _(this.categories()).find(function(cat){ return cat.id == id; }); },
  • var TodoList = Backbone.Collection.extend({ model: Todo, localStorage: new Store("todos-backbone"), done: function () { return this.filter(function (todo) { return todo.get(done); }); }, remaining: function () { return this.without.apply(this, this.done()); }, nextOrder: function () { if (!this.length) return 1; return this.last().get(order) + 1; }, comparator: function (todo) { return todo.get(order); }});
  • var accounts = new Backbone.Collection;accounts.url = /accounts;accounts.fetch();
  • Routers• Page Routing• Control Flow• Stateful, Bookmarkable
  • TestRouter = Backbone.Router.extend({ routes: { "": "home", "foo": "foo", "bar/:name": "somefunction" }, home: function () { }, foo: function () { alert(hi from foo); }, somefunction: function (name) { alert(name); }});
  • Eventsvar object = {};_.extend(object, Backbone.Events);object.on("alert", function(msg) { alert("Triggered " + msg);});object.trigger("alert", "an event");
  • Other• History – a global router (per frame) to handle hashchange events or pushState – matchs the appropriate route, and trigger callbacks• Backbone.sync – method: the CRUD method – model: the model to be saved (or collection to be read) – options: success and error callbacks, and all other jQuery request options
  • Catalog of Events• "add" (model, collection) — when a model is added to a collection.• "remove" (model, collection) — when a model is removed from a collection.• "reset" (collection) — when the collections entire contents have been replaced.• "change" (model, options) — when a models attributes have changed.• "change:[attribute]" (model, value, options) — when a specific attribute has been updated.• "destroy" (model, collection) — when a model is destroyed.• "sync" (model, collection) — triggers whenever a model has been successfully synced to the server.• "error" (model, collection) — when a models validation fails, or a save call fails on the server.• "route:[name]" (router) — when one of a routers routes has matched.• "all" — this special event fires for any triggered event, passing the event name as the first argument.
  • Advanced• CoffeeScript• AMD/Require.js
  • Get StartedGithub sitehttp://documentcloud.github.com/backbone/Backbone Fundamentalshttps://github.com/addyosmani/backbone-fundamentalsTodoMVChttp://addyosmani.github.com/todomvc/