From a2a1bf99f9c0535143059f71890e5b61bda9473d Mon Sep 17 00:00:00 2001
From: Brad Dunbar
+
+
Examples
@@ -491,20 +505,6 @@
-
-
Change Log
@@ -2805,1207 +2805,1207 @@ Utility
this is the property for you.
- The list of examples that follows, while long, is not exhaustive. If you've - worked on an app that uses Backbone, please add it to the - wiki page of Backbone apps. +
+ Why use Backbone, not [other framework X]?
+
+ If your eye hasn't already been caught by the adaptability and elan on display
+ in the above list of examples, we can get more specific:
+ Backbone.js aims to provide the common foundation that data-rich web applications
+ with ambitious interfaces require — while very deliberately avoiding
+ painting you into a corner by making any decisions that you're
+ better equipped to make yourself.
- Jérôme Gravel-Niquet has contributed a - Todo List application - that is bundled in the repository as Backbone example. If you're wondering - where to get started with Backbone in general, take a moment to - read through the annotated source. The app uses a - LocalStorage adapter - to transparently save all of your todos within your browser, instead of - sending them to a server. Jérôme also has a version hosted at - localtodos.com. -
+
+ There's More Than One Way To Do It
+
+ It's common for folks just getting started to treat the examples listed
+ on this page as some sort of gospel truth. In fact, Backbone.js is intended
+ to be fairly agnostic about many common patterns in client-side code.
+ For example...
+
+ References between Models and Views can be handled several ways. + Some people like to have direct pointers, where views correspond 1:1 with + models (model.view and view.model). Others prefer to have intermediate + "controller" objects that orchestrate the creation and organization of + views into a hierarchy. Others still prefer the evented approach, and always + fire events instead of calling methods directly. All of these styles work well. +
- The DocumentCloud workspace - is built on Backbone.js, with Documents, Projects, - Notes, and Accounts all as Backbone models and collections. - If you're interested in history — both Underscore.js and Backbone.js - were originally extracted from the DocumentCloud codebase, and packaged - into standalone JS libraries. + Batch operations on Models are common, but often best handled differently + depending on your server-side setup. Some folks don't mind making individual + Ajax requests. Others create explicit resources for RESTful batch operations: + /notes/batch/destroy?ids=1,2,3,4. Others tunnel REST over JSON, with the + creation of "changeset" requests:
-+ { + "create": [array of models to create] + "update": [array of models to update] + "destroy": [array of model ids to destroy] + } +-
+ Feel free to define your own events. Backbone.Events + is designed so that you can mix it in to any JavaScript object or prototype. + Since you can use any string as an event, it's often handy to bind + and trigger your own custom events: model.on("selected:true") or + model.on("editing") +
- USA Today takes advantage of the modularity of - Backbone's data/model lifecycle — which makes it simple to create, inherit, - isolate, and link application objects — to keep the codebase both manageable and efficient. - The new website also makes heavy use of the Backbone Router to control the - page for both pushState-capable and legacy browsers. - Finally, the team took advantage of Backbone's Event module to create a - PubSub API that allows third parties and analytics packages to hook into the - heart of the app. + Render the UI as you see fit. Backbone is agnostic as to whether you + use Underscore templates, + Mustache.js, direct DOM + manipulation, server-side rendered snippets of HTML, or + jQuery UI in your render function. + Sometimes you'll create a view for each model ... sometimes you'll have a + view that renders thousands of models at once, in a tight loop. Both can be + appropriate in the same app, depending on the quantity of data involved, + and the complexity of the UI.
-
+ Nested Models & Collections
+
+ It's common to nest collections inside of models with Backbone. For example,
+ consider a Mailbox model that contains many Message models.
+ One nice pattern for handling this is have a this.messages collection
+ for each mailbox, enabling the lazy-loading of messages, when the mailbox
+ is first opened ... perhaps with MessageList views listening for
+ "add" and "remove" events.
+
+var Mailbox = Backbone.Model.extend({ -- New Rdio was developed from the ground - up with a component based framework based on Backbone.js. Every component - on the screen is dynamically loaded and rendered, with data provided by the - Rdio API. When changes are pushed, - every component can update itself without reloading the page or interrupting - the user's music. All of this relies on Backbone's views and models, - and all URL routing is handled by Backbone's Router. When data changes are - signaled in realtime, Backbone's Events notify the interested components - in the data changes. Backbone forms the core of the new, dynamic, realtime - Rdio web and desktop applications. -
+ initialize: function() { + this.messages = new Messages; + this.messages.url = '/mailbox/' + this.id + '/messages'; + this.messages.on("reset", this.updateCounts); + }, -- - - -+ ... -Hulu
+}); -- Hulu used Backbone.js to build its next - generation online video experience. With Backbone as a foundation, the - web interface was rewritten from scratch so that all page content can - be loaded dynamically with smooth transitions as you navigate. - Backbone makes it easy to move through the app quickly without the - reloading of scripts and embedded videos, while also offering models and - collections for additional data manipulation support. -
+var inbox = new Mailbox; -- - - -+// And then, when the Inbox is opened: -Quartz
+inbox.messages.fetch({reset: true}); +
- Quartz sees itself as a digitally native news - outlet for the new - global economy. Because Quartz believes in the future of open, - cross-platform web applications, they selected Backbone and Underscore - to fetch, sort, store, and display content from a custom WordPress - API. Although qz.com uses responsive design - for phone, tablet, and - desktop browsers, it also takes advantage of Backbone events and views - to render device-specific templates in some cases. + If you're looking for something more opinionated, there are a number of + Backbone plugins that add sophisticated associations among models, + available on the wiki.
-- Kinja is Gawker Media's publishing platform designed - to create great stories by breaking down the lines between the traditional - roles of content creators and consumers. Everyone — editors, readers, - marketers — have access to the same tools to engage in passionate discussion - and pursue the truth of the story. Sharing, recommending, and following within the - Kinja ecosystem allows for improved information discovery across all the sites. -
-- Kinja is the platform behind - Gawker, - Gizmodo, - Lifehacker, - io9 and other Gawker Media - blogs. Backbone.js underlies the front-end application code that powers - everything from user authentication to post authoring, commenting, and even serving - ads. The JavaScript stack includes - Underscore.js and - jQuery, with some plugins, - all loaded with - RequireJS. Closure templates are shared between the - Play! Framework based Scala application and Backbone views, and the responsive layout - is done with the - Foundation framework using - SASS. -
- -- MetaLab used Backbone.js to create - Flow, a task management app for teams. The - workspace relies on Backbone.js to construct task views, activities, accounts, - folders, projects, and tags. You can see the internals under window.Flow. -
- -- Gilt Groupe uses Backbone.js to build multiple - applications across their family of sites. - Gilt's mobile website uses Backbone and - Zepto.js to create a blazing-fast - shopping experience for users on-the-go, while - Gilt Live combines Backbone with - WebSockets to display the items that customers are buying in real-time. Gilt's search - functionality also uses Backbone to filter and sort products efficiently - by moving those actions to the client-side. + Backbone doesn't include direct support for nested models and collections + or "has many" associations because there are a number + of good patterns for modeling structured data on the client side, and + Backbone should provide the foundation for implementing any of them. + You may want to…
-- NewsBlur is an RSS feed reader and - social news network with a fast and responsive UI that feels like a - native desktop app. Backbone.js was selected for - a major rewrite and transition from spaghetti code - because of its powerful yet simple feature set, easy integration, and large - community. If you want to poke around under the hood, NewsBlur is also entirely - open-source. +
+ Loading Bootstrapped Models
+
+ When your app first loads, it's common to have a set of initial models that
+ you know you're going to need, in order to render the page. Instead of
+ firing an extra AJAX request to fetch them,
+ a nicer pattern is to have their data already bootstrapped into the page.
+ You can then use reset to populate your
+ collections with the initial data. At DocumentCloud, in the
+ ERB template for the
+ workspace, we do something along these lines:
+<script> + var accounts = new Backbone.Collection; + accounts.reset(<%= @accounts.to_json %>); + var projects = new Backbone.Collection; + projects.reset(<%= @projects.to_json(:collaborators => true) %>); +</script> +-
You have to escape + </ within the JSON string, to prevent javascript injection + attacks. -
- WordPress.com is the software-as-a-service - version of WordPress. It uses Backbone.js - Models, Collections, and Views in its - Notifications system. Backbone.js was selected - because it was easy to fit into the structure of the application, not the - other way around. Automattic - (the company behind WordPress.com) is integrating Backbone.js into the - Stats tab and other features throughout the homepage. +
+ Extending Backbone
+
+ Many JavaScript libraries are meant to be insular and self-enclosed,
+ where you interact with them by calling their public API, but never peek
+ inside at the guts. Backbone.js is not that kind of library.
- Foursquare is a fun little startup that helps you meet up with friends, - discover new places, and save money. Backbone Models are heavily used in - the core JavaScript API layer and Views power many popular features like - the homepage map and - lists. + Because it serves as a foundation for your application, you're meant to + extend and enhance it in the ways you see fit — the entire source + code is annotated to make this easier + for you. You'll find that there's very little there apart from core + functions, and most of those can be overriden or augmented should you find + the need. If you catch yourself adding methods to Backbone.Model.prototype, + or creating your own base subclass, don't worry — that's how things are + supposed to work.
-- Bitbucket is a free source code hosting - service for Git and Mercurial. Through its models and collections, - Backbone.js has proved valuable in supporting Bitbucket's - REST API, as well as newer - components such as in-line code comments and approvals for pull requests. - Mustache templates provide server and client-side rendering, while a custom - Google Closure - inspired life-cycle for widgets allows Bitbucket to decorate existing DOM - trees and insert new ones. +
+ How does Backbone relate to "traditional" MVC?
+
+ Different implementations of the
+ Model-View-Controller
+ pattern tend to disagree about the definition of a controller. If it helps any, in
+ Backbone, the View class can also be thought of as a
+ kind of controller, dispatching events that originate from the UI, with
+ the HTML template serving as the true view. We call it a View because it
+ represents a logical chunk of UI, responsible for the contents of a single
+ DOM element.
- Disqus chose Backbone.js to power the - latest version of their commenting widget. Backbone’s small - footprint and easy extensibility made it the right choice for Disqus’ - distributed web application, which is hosted entirely inside an iframe and - served on thousands of large web properties, including IGN, Wired, CNN, MLB, and more. + Comparing the overall structure of Backbone to a server-side MVC framework + like Rails, the pieces line up like so:
-- Delicious is a social bookmarking - platform making it easy to save, sort, and store bookmarks from across - the web. Delicious uses Chaplin.js, - Backbone.js and AppCache to build a full-featured MVC web app. - The use of Backbone helped the website and - mobile apps share a - single API service, and the reuse of the model tier made it significantly - easier to share code during the recent Delicious redesign. +
+ Binding "this"
+
+ Perhaps the single most common JavaScript "gotcha" is the fact that when
+ you pass a function as a callback, its value for this is lost.
+ When dealing with events and callbacks in Backbone,
+ you'll often find it useful to rely on listenTo
+ or the optional context argument that many of Underscore
+ and Backbone's methods use to specify the this
+ that will be used when the callback is later invoked. (See
+ _.each,
+ _.map, and
+ object.on, to name a few).
+ View events are automatically bound to
+ the view's context for you.
+ You may also find it helpful to use
+ _.bind and
+ _.bindAll
+ from Underscore.js.
+var MessageList = Backbone.View.extend({ --- Khan Academy is on a mission to - provide a free world-class education to anyone anywhere. With thousands of - videos, hundreds of JavaScript-driven exercises, and big plans for the - future, Khan Academy uses Backbone to keep frontend code modular and organized. - User profiles and goal setting are implemented with Backbone, - jQuery and - Handlebars, and most new feature - work is being pushed to the client side, greatly increasing the quality of - the API. -
+ initialize: function() { + var messages = this.collection; + messages.on("reset", this.render, this); + messages.on("add", this.addMessage, this); + messages.on("remove", this.removeMessage, this); -- - - -+ messsages.each(this.addMessage, this); + } -eLife Lens
+}); -- eLife Lens - is a novel system for writing on the web. Instead of tying the content to a - presentation focused format, Lens treats - content as data - and makes the links that exist within a document easy to navigate. Backbone.js - is used to structure the views, - Substance Document - for representing content and - Ken - for faceted filtering. Read more in the official - introduction post - or dig into the source code. -
+// Later, in the app... -- - - -+Inbox.messages.add(newMessage); +
+ Working with Rails
+
+ Backbone.js was originally extracted from
+ a Rails application; getting
+ your client-side (Backbone) Models to sync correctly with your server-side
+ (Rails) Models is painless, but there are still a few things to be aware of.
+
- Do is a social productivity app that makes it - easy to work on tasks, track projects, and take notes with your team. - The Do.com web application was built from the - ground up to work seamlessly on your smartphone, tablet and computer. The - team used Backbone, CoffeeScript and Handlebars to build a full-featured - app in record time and rolled their own extensions for complex navigation - and model sync support. + By default, Rails versions prior to 3.1 add an extra layer of wrapping + around the JSON representation of models. You can disable this wrapping + by setting:
-+ActiveRecord::Base.include_root_in_json = false +
- IRCCloud - is an always-connected IRC client that you use in your - browser — often leaving it open all day in a tab. - The sleek web interface communicates with an - Erlang backend via websockets and the - IRCCloud API. - It makes heavy use of Backbone.js events, models, views and routing to keep - your IRC conversations flowing in real time. + ... in your configuration. Otherwise, override + parse to pull model attributes out of the + wrapper. Similarly, Backbone PUTs and POSTs direct JSON representations + of models, where by default Rails expects namespaced attributes. You can + have your controllers filter attributes directly from params, or + you can override toJSON in Backbone to add + the extra wrapping Rails expects.
-- Pitchfork uses Backbone.js to power - its site-wide audio player, Pitchfork.tv, - location routing, a write-thru page fragment cache, and more. Backbone.js - (and Underscore.js) helps the team - create clean and modular components, - move very quickly, and focus on the site, not the spaghetti. + The list of examples that follows, while long, is not exhaustive. If you've + worked on an app that uses Backbone, please add it to the + wiki page of Backbone apps. +
+ ++ Jérôme Gravel-Niquet has contributed a + Todo List application + that is bundled in the repository as Backbone example. If you're wondering + where to get started with Backbone in general, take a moment to + read through the annotated source. The app uses a + LocalStorage adapter + to transparently save all of your todos within your browser, instead of + sending them to a server. Jérôme also has a version hosted at + localtodos.com.
-- Spin pulls in the - latest news stories from - their internal API onto their site using Backbone models and collections, and a - custom sync method. Because the music should never stop playing, - even as you click through to different "pages", Spin uses a Backbone router - for navigation within the site. + The DocumentCloud workspace + is built on Backbone.js, with Documents, Projects, + Notes, and Accounts all as Backbone models and collections. + If you're interested in history — both Underscore.js and Backbone.js + were originally extracted from the DocumentCloud codebase, and packaged + into standalone JS libraries.
-- ZocDoc helps patients - find local, in-network doctors and dentists, see their real-time - availability, and instantly book appointments. - On the public side, the webapp uses Backbone.js to handle client-side state and rendering in - search pages - and doctor profiles. - In addition, the new version of the doctor-facing part of the website is a - large single-page application that - benefits from Backbone's structure and modularity. ZocDoc's Backbone - classes are tested with - Jasmine, and delivered - to the end user with - Cassette. + USA Today takes advantage of the modularity of + Backbone's data/model lifecycle — which makes it simple to create, inherit, + isolate, and link application objects — to keep the codebase both manageable and efficient. + The new website also makes heavy use of the Backbone Router to control the + page for both pushState-capable and legacy browsers. + Finally, the team took advantage of Backbone's Event module to create a + PubSub API that allows third parties and analytics packages to hook into the + heart of the app.
-- Walmart used Backbone.js to create the new version - of their mobile web application and - created two new frameworks in the process. - Thorax provides mixins, inheritable - events, as well as model and collection view bindings that integrate directly with - Handlebars templates. - Lumbar allows the application to be - split into modules which can be loaded on demand, and creates platform specific builds - for the portions of the web application that are embedded in Walmart's native Android - and iOS applications. + New Rdio was developed from the ground + up with a component based framework based on Backbone.js. Every component + on the screen is dynamically loaded and rendered, with data provided by the + Rdio API. When changes are pushed, + every component can update itself without reloading the page or interrupting + the user's music. All of this relies on Backbone's views and models, + and all URL routing is handled by Backbone's Router. When data changes are + signaled in realtime, Backbone's Events notify the interested components + in the data changes. Backbone forms the core of the new, dynamic, realtime + Rdio web and desktop applications.
-- Groupon Now! helps you find - local deals that you can buy and use right now. When first developing - the product, the team decided it would be AJAX heavy with smooth transitions - between sections instead of full refreshes, but still needed to be fully - linkable and shareable. Despite never having used Backbone before, the - learning curve was incredibly quick — a prototype was hacked out in an - afternoon, and the team was able to ship the product in two weeks. - Because the source is minimal and understandable, it was easy to - add several Backbone extensions for Groupon Now!: changing the router - to handle URLs with querystring parameters, and adding a simple - in-memory store for caching repeated requests for the same data. + Hulu used Backbone.js to build its next + generation online video experience. With Backbone as a foundation, the + web interface was rewritten from scratch so that all page content can + be loaded dynamically with smooth transitions as you navigate. + Backbone makes it easy to move through the app quickly without the + reloading of scripts and embedded videos, while also offering models and + collections for additional data manipulation support.
-- 37Signals chose Backbone.js to create - the calendar feature of its - popular project management software Basecamp. - The Basecamp Calendar uses Backbone.js models and views in conjunction with the - Eco templating system to - present a polished, highly interactive group scheduling interface. + Quartz sees itself as a digitally native news + outlet for the new + global economy. Because Quartz believes in the future of open, + cross-platform web applications, they selected Backbone and Underscore + to fetch, sort, store, and display content from a custom WordPress + API. Although qz.com uses responsive design + for phone, tablet, and + desktop browsers, it also takes advantage of Backbone events and views + to render device-specific templates in some cases.
-- Slavery Footprint - allows consumers to visualize how their consumption habits are - connected to modern-day slavery and provides them with an opportunity - to have a deeper conversation with the companies that manufacture the - goods they purchased. - Based in Oakland, California, the Slavery Footprint team works to engage - individuals, groups, and businesses to build awareness for and create - deployable action against forced labor, human trafficking, and modern-day - slavery through online tools, as well as off-line community education and - mobilization programs. + Kinja is Gawker Media's publishing platform designed + to create great stories by breaking down the lines between the traditional + roles of content creators and consumers. Everyone — editors, readers, + marketers — have access to the same tools to engage in passionate discussion + and pursue the truth of the story. Sharing, recommending, and following within the + Kinja ecosystem allows for improved information discovery across all the sites. +
++ Kinja is the platform behind + Gawker, + Gizmodo, + Lifehacker, + io9 and other Gawker Media + blogs. Backbone.js underlies the front-end application code that powers + everything from user authentication to post authoring, commenting, and even serving + ads. The JavaScript stack includes + Underscore.js and + jQuery, with some plugins, + all loaded with + RequireJS. Closure templates are shared between the + Play! Framework based Scala application and Backbone views, and the responsive layout + is done with the + Foundation framework using + SASS.
-- Stripe provides an API for accepting - credit cards on the web. Stripe's - management interface was recently - rewritten from scratch in CoffeeScript using Backbone.js as the primary - framework, Eco for templates, Sass for stylesheets, and Stitch to package - everything together as CommonJS modules. The new app uses - Stripe's API directly for the - majority of its actions; Backbone.js models made it simple to map - client-side models to their corresponding RESTful resources. + MetaLab used Backbone.js to create + Flow, a task management app for teams. The + workspace relies on Backbone.js to construct task views, activities, accounts, + folders, projects, and tags. You can see the internals under window.Flow.
-- Airbnb uses Backbone in many of its products. - It started with Airbnb Mobile Web - (built in six weeks by a team of three) and has since grown to - Wish Lists, - Match, - Search, Communities, Payments, and - Internal Tools. + Gilt Groupe uses Backbone.js to build multiple + applications across their family of sites. + Gilt's mobile website uses Backbone and + Zepto.js to create a blazing-fast + shopping experience for users on-the-go, while + Gilt Live combines Backbone with + WebSockets to display the items that customers are buying in real-time. Gilt's search + functionality also uses Backbone to filter and sort products efficiently + by moving those actions to the client-side.
-- SoundCloud is the leading sound sharing - platform on the internet, and Backbone.js provides the foundation for - SoundCloud Mobile. The project uses - the public SoundCloud API - as a data source (channeled through a nginx proxy), - jQuery templates - for the rendering, Qunit - and PhantomJS for - the testing suite. The JS code, templates and CSS are built for the - production deployment with various Node.js tools like - ready.js, - Jake, - jsdom. - The Backbone.History was modified to support the HTML5 history.pushState. - Backbone.sync was extended with an additional SessionStorage based cache - layer. + NewsBlur is an RSS feed reader and + social news network with a fast and responsive UI that feels like a + native desktop app. Backbone.js was selected for + a major rewrite and transition from spaghetti code + because of its powerful yet simple feature set, easy integration, and large + community. If you want to poke around under the hood, NewsBlur is also entirely + open-source.
-- Art.sy is a place to discover art you'll - love. Art.sy is built on Rails, using - Grape to serve a robust - JSON API. The main site is a single page - app written in CoffeeScript and uses Backbone to provide structure around - this API. An admin panel and partner CMS have also been extracted into - their own API-consuming Backbone projects. + WordPress.com is the software-as-a-service + version of WordPress. It uses Backbone.js + Models, Collections, and Views in its + Notifications system. Backbone.js was selected + because it was easy to fit into the structure of the application, not the + other way around. Automattic + (the company behind WordPress.com) is integrating Backbone.js into the + Stats tab and other features throughout the homepage.
-- When Pandora redesigned - their site in HTML5, they chose Backbone.js to help - manage the user interface and interactions. For example, there's a model - that represents the "currently playing track", and multiple views that - automatically update when the current track changes. The station list is a - collection, so that when stations are added or changed, the UI stays up to date. + Foursquare is a fun little startup that helps you meet up with friends, + discover new places, and save money. Backbone Models are heavily used in + the core JavaScript API layer and Views power many popular features like + the homepage map and + lists.
-- Inkling is a cross-platform way to - publish interactive learning content. - Inkling for Web uses Backbone.js - to make hundreds of complex books — from student textbooks to travel guides and - programming manuals — engaging and accessible on the web. Inkling supports - WebGL-enabled 3D graphics, interactive assessments, social sharing, - and a system for running practice code right - in the book, all within a single page Backbone-driven app. Early on, the - team decided to keep the site lightweight by using only Backbone.js and - raw JavaScript. The result? Complete source code weighing in at a mere - 350kb with feature-parity across the iPad, iPhone and web clients. - Give it a try with - this excerpt from JavaScript: The Definitive Guide. + Bitbucket is a free source code hosting + service for Git and Mercurial. Through its models and collections, + Backbone.js has proved valuable in supporting Bitbucket's + REST API, as well as newer + components such as in-line code comments and approvals for pull requests. + Mustache templates provide server and client-side rendering, while a custom + Google Closure + inspired life-cycle for widgets allows Bitbucket to decorate existing DOM + trees and insert new ones.
-- Code School courses teach people - about various programming topics like CoffeeScript, CSS, Ruby on Rails, - and more. The new Code School course - challenge page - is built from the ground up on Backbone.js, using - everything it has to offer: the router, collections, models, and complex - event handling. Before, the page was a mess of jQuery DOM manipulation - and manual Ajax calls. Backbone.js helped introduce a new way to - think about developing an organized front-end application in JavaScript. + Disqus chose Backbone.js to power the + latest version of their commenting widget. Backbone’s small + footprint and easy extensibility made it the right choice for Disqus’ + distributed web application, which is hosted entirely inside an iframe and + served on thousands of large web properties, including IGN, Wired, CNN, MLB, and more.
-- CloudApp is simple file and link - sharing for the Mac. Backbone.js powers the web tools - which consume the documented API - to manage Drops. Data is either pulled manually or pushed by - Pusher and fed to - Mustache templates for - rendering. Check out the annotated source code - to see the magic. + Delicious is a social bookmarking + platform making it easy to save, sort, and store bookmarks from across + the web. Delicious uses Chaplin.js, + Backbone.js and AppCache to build a full-featured MVC web app. + The use of Backbone helped the website and + mobile apps share a + single API service, and the reuse of the model tier made it significantly + easier to share code during the recent Delicious redesign.
-- SeatGeek's stadium ticket maps were originally - developed with Prototype.js. Moving to Backbone.js and jQuery helped organize - a lot of the UI code, and the increased structure has made adding features - a lot easier. SeatGeek is also in the process of building a mobile - interface that will be Backbone.js from top to bottom. + Khan Academy is on a mission to + provide a free world-class education to anyone anywhere. With thousands of + videos, hundreds of JavaScript-driven exercises, and big plans for the + future, Khan Academy uses Backbone to keep frontend code modular and organized. + User profiles and goal setting are implemented with Backbone, + jQuery and + Handlebars, and most new feature + work is being pushed to the client side, greatly increasing the quality of + the API.
-- Easel is an in-browser, high fidelity web - design tool that integrates with your design and development - process. The Easel team uses CoffeeScript, Underscore.js and Backbone.js for - their rich visual editor as well as other - management functions throughout the site. The structure of Backbone allowed - the team to break the complex problem of building a visual editor into - manageable components and still move quickly. + eLife Lens + is a novel system for writing on the web. Instead of tying the content to a + presentation focused format, Lens treats + content as data + and makes the links that exist within a document easy to navigate. Backbone.js + is used to structure the views, + Substance Document + for representing content and + Ken + for faceted filtering. Read more in the official + introduction post + or dig into the source code.
-- Jolicloud is an open and independent - platform and operating system - that provides music playback, video streaming, photo browsing and - document editing — transforming low cost computers into beautiful cloud devices. - The new Jolicloud HTML5 app was built - from the ground up using Backbone and talks to the - Jolicloud Platform, which is - based on Node.js. Jolicloud works offline using the HTML5 AppCache, extends - Backbone.sync to store data in IndexedDB or localStorage, and communicates - with the Joli OS via WebSockets. + Do is a social productivity app that makes it + easy to work on tasks, track projects, and take notes with your team. + The Do.com web application was built from the + ground up to work seamlessly on your smartphone, tablet and computer. The + team used Backbone, CoffeeScript and Handlebars to build a full-featured + app in record time and rolled their own extensions for complex navigation + and model sync support.
-- Syllabus - is the new live blogging platform used by - The Verge - and other Vox Media sites. - Syllabus uses Backbone on both ends: an editorial dashboard and the live blog - page itself. In the back, Backbone is used to provide a - single-page experience for uploading, writing, editing and publishing content. - On the live blog, Backbone manages fetching a JSON API feed, and updating - the infinite-scrolling river of updates with new and revised content. + IRCCloud + is an always-connected IRC client that you use in your + browser — often leaving it open all day in a tab. + The sleek web interface communicates with an + Erlang backend via websockets and the + IRCCloud API. + It makes heavy use of Backbone.js events, models, views and routing to keep + your IRC conversations flowing in real time.
-- Salon.io provides a space where photographers, - artists and designers freely arrange their visual art on virtual walls. - Salon.io runs on Rails, but does not use - much of the traditional stack, as the entire frontend is designed as a - single page web app, using Backbone.js, Brunch and - CoffeeScript. + Pitchfork uses Backbone.js to power + its site-wide audio player, Pitchfork.tv, + location routing, a write-thru page fragment cache, and more. Backbone.js + (and Underscore.js) helps the team + create clean and modular components, + move very quickly, and focus on the site, not the spaghetti.
-- Our fellow - Knight Foundation News Challenge - winners, MapBox, created an open-source - map design studio with Backbone.js: - TileMill. - TileMill lets you manage map layers based on shapefiles and rasters, and - edit their appearance directly in the browser with the - Carto styling language. - Note that the gorgeous MapBox homepage - is also a Backbone.js app. + Spin pulls in the + latest news stories from + their internal API onto their site using Backbone models and collections, and a + custom sync method. Because the music should never stop playing, + even as you click through to different "pages", Spin uses a Backbone router + for navigation within the site.
-- Blossom is a lightweight project management - tool for lean teams. Backbone.js is heavily used in combination with - CoffeeScript to provide a smooth - interaction experience. The app is packaged with Brunch. - The RESTful backend is built with Flask on Google App Engine. + ZocDoc helps patients + find local, in-network doctors and dentists, see their real-time + availability, and instantly book appointments. + On the public side, the webapp uses Backbone.js to handle client-side state and rendering in + search pages + and doctor profiles. + In addition, the new version of the doctor-facing part of the website is a + large single-page application that + benefits from Backbone's structure and modularity. ZocDoc's Backbone + classes are tested with + Jasmine, and delivered + to the end user with + Cassette.
-- Trello is a collaboration tool that - organizes your projects into boards. A Trello board holds many lists of - cards, which can contain checklists, files and conversations, and may be - voted on and organized with labels. Updates on the board happen in - real time. The site was built ground up using Backbone.js for all the - models, views, and routes. + Walmart used Backbone.js to create the new version + of their mobile web application and + created two new frameworks in the process. + Thorax provides mixins, inheritable + events, as well as model and collection view bindings that integrate directly with + Handlebars templates. + Lumbar allows the application to be + split into modules which can be loaded on demand, and creates platform specific builds + for the portions of the web application that are embedded in Walmart's native Android + and iOS applications.
-- Cristi Balan and - Irina Dumitrascu created - Tzigla, a collaborative drawing - application where artists make tiles that connect to each other to - create surreal drawings. - Backbone models help organize the code, routers provide - bookmarkable deep links, - and the views are rendered with - haml.js and - Zepto. - Tzigla is written in Ruby (Rails) on the backend, and - CoffeeScript on the frontend, with - Jammit - prepackaging the static assets. + Groupon Now! helps you find + local deals that you can buy and use right now. When first developing + the product, the team decided it would be AJAX heavy with smooth transitions + between sections instead of full refreshes, but still needed to be fully + linkable and shareable. Despite never having used Backbone before, the + learning curve was incredibly quick — a prototype was hacked out in an + afternoon, and the team was able to ship the product in two weeks. + Because the source is minimal and understandable, it was easy to + add several Backbone extensions for Groupon Now!: changing the router + to handle URLs with querystring parameters, and adding a simple + in-memory store for caching repeated requests for the same data.
-
- Why use Backbone, not [other framework X]?
-
- If your eye hasn't already been caught by the adaptability and elan on display
- in the above list of examples, we can get more specific:
- Backbone.js aims to provide the common foundation that data-rich web applications
- with ambitious interfaces require — while very deliberately avoiding
- painting you into a corner by making any decisions that you're
- better equipped to make yourself.
-
- There's More Than One Way To Do It
-
- It's common for folks just getting started to treat the examples listed
- on this page as some sort of gospel truth. In fact, Backbone.js is intended
- to be fairly agnostic about many common patterns in client-side code.
- For example...
+
+ 37Signals chose Backbone.js to create + the calendar feature of its + popular project management software Basecamp. + The Basecamp Calendar uses Backbone.js models and views in conjunction with the + Eco templating system to + present a polished, highly interactive group scheduling interface.
+- References between Models and Views can be handled several ways. - Some people like to have direct pointers, where views correspond 1:1 with - models (model.view and view.model). Others prefer to have intermediate - "controller" objects that orchestrate the creation and organization of - views into a hierarchy. Others still prefer the evented approach, and always - fire events instead of calling methods directly. All of these styles work well. + Slavery Footprint + allows consumers to visualize how their consumption habits are + connected to modern-day slavery and provides them with an opportunity + to have a deeper conversation with the companies that manufacture the + goods they purchased. + Based in Oakland, California, the Slavery Footprint team works to engage + individuals, groups, and businesses to build awareness for and create + deployable action against forced labor, human trafficking, and modern-day + slavery through online tools, as well as off-line community education and + mobilization programs.
+- Batch operations on Models are common, but often best handled differently - depending on your server-side setup. Some folks don't mind making individual - Ajax requests. Others create explicit resources for RESTful batch operations: - /notes/batch/destroy?ids=1,2,3,4. Others tunnel REST over JSON, with the - creation of "changeset" requests: + Stripe provides an API for accepting + credit cards on the web. Stripe's + management interface was recently + rewritten from scratch in CoffeeScript using Backbone.js as the primary + framework, Eco for templates, Sass for stylesheets, and Stitch to package + everything together as CommonJS modules. The new app uses + Stripe's API directly for the + majority of its actions; Backbone.js models made it simple to map + client-side models to their corresponding RESTful resources.
-- { - "create": [array of models to create] - "update": [array of models to update] - "destroy": [array of model ids to destroy] - } -+
- Feel free to define your own events. Backbone.Events - is designed so that you can mix it in to any JavaScript object or prototype. - Since you can use any string as an event, it's often handy to bind - and trigger your own custom events: model.on("selected:true") or - model.on("editing") + Airbnb uses Backbone in many of its products. + It started with Airbnb Mobile Web + (built in six weeks by a team of three) and has since grown to + Wish Lists, + Match, + Search, Communities, Payments, and + Internal Tools.
+- Render the UI as you see fit. Backbone is agnostic as to whether you - use Underscore templates, - Mustache.js, direct DOM - manipulation, server-side rendered snippets of HTML, or - jQuery UI in your render function. - Sometimes you'll create a view for each model ... sometimes you'll have a - view that renders thousands of models at once, in a tight loop. Both can be - appropriate in the same app, depending on the quantity of data involved, - and the complexity of the UI. + SoundCloud is the leading sound sharing + platform on the internet, and Backbone.js provides the foundation for + SoundCloud Mobile. The project uses + the public SoundCloud API + as a data source (channeled through a nginx proxy), + jQuery templates + for the rendering, Qunit + and PhantomJS for + the testing suite. The JS code, templates and CSS are built for the + production deployment with various Node.js tools like + ready.js, + Jake, + jsdom. + The Backbone.History was modified to support the HTML5 history.pushState. + Backbone.sync was extended with an additional SessionStorage based cache + layer.
-
- Nested Models & Collections
-
- It's common to nest collections inside of models with Backbone. For example,
- consider a Mailbox model that contains many Message models.
- One nice pattern for handling this is have a this.messages collection
- for each mailbox, enabling the lazy-loading of messages, when the mailbox
- is first opened ... perhaps with MessageList views listening for
- "add" and "remove" events.
-
-var Mailbox = Backbone.Model.extend({ ++Art.sy
- initialize: function() { - this.messages = new Messages; - this.messages.url = '/mailbox/' + this.id + '/messages'; - this.messages.on("reset", this.updateCounts); - }, ++ Art.sy is a place to discover art you'll + love. Art.sy is built on Rails, using + Grape to serve a robust + JSON API. The main site is a single page + app written in CoffeeScript and uses Backbone to provide structure around + this API. An admin panel and partner CMS have also been extracted into + their own API-consuming Backbone projects. +
- ... ++ + + +-}); +Pandora
-var inbox = new Mailbox; ++ When Pandora redesigned + their site in HTML5, they chose Backbone.js to help + manage the user interface and interactions. For example, there's a model + that represents the "currently playing track", and multiple views that + automatically update when the current track changes. The station list is a + collection, so that when stations are added or changed, the UI stays up to date. +
-// And then, when the Inbox is opened: ++ + + +-inbox.messages.fetch({reset: true}); -
- If you're looking for something more opinionated, there are a number of - Backbone plugins that add sophisticated associations among models, - available on the wiki. + Inkling is a cross-platform way to + publish interactive learning content. + Inkling for Web uses Backbone.js + to make hundreds of complex books — from student textbooks to travel guides and + programming manuals — engaging and accessible on the web. Inkling supports + WebGL-enabled 3D graphics, interactive assessments, social sharing, + and a system for running practice code right + in the book, all within a single page Backbone-driven app. Early on, the + team decided to keep the site lightweight by using only Backbone.js and + raw JavaScript. The result? Complete source code weighing in at a mere + 350kb with feature-parity across the iPad, iPhone and web clients. + Give it a try with + this excerpt from JavaScript: The Definitive Guide.
+- Backbone doesn't include direct support for nested models and collections - or "has many" associations because there are a number - of good patterns for modeling structured data on the client side, and - Backbone should provide the foundation for implementing any of them. - You may want to… + Code School courses teach people + about various programming topics like CoffeeScript, CSS, Ruby on Rails, + and more. The new Code School course + challenge page + is built from the ground up on Backbone.js, using + everything it has to offer: the router, collections, models, and complex + event handling. Before, the page was a mess of jQuery DOM manipulation + and manual Ajax calls. Backbone.js helped introduce a new way to + think about developing an organized front-end application in JavaScript.
-
- Loading Bootstrapped Models
-
- When your app first loads, it's common to have a set of initial models that
- you know you're going to need, in order to render the page. Instead of
- firing an extra AJAX request to fetch them,
- a nicer pattern is to have their data already bootstrapped into the page.
- You can then use reset to populate your
- collections with the initial data. At DocumentCloud, in the
- ERB template for the
- workspace, we do something along these lines:
+
+ CloudApp is simple file and link + sharing for the Mac. Backbone.js powers the web tools + which consume the documented API + to manage Drops. Data is either pulled manually or pushed by + Pusher and fed to + Mustache templates for + rendering. Check out the annotated source code + to see the magic. +
+ ++ SeatGeek's stadium ticket maps were originally + developed with Prototype.js. Moving to Backbone.js and jQuery helped organize + a lot of the UI code, and the increased structure has made adding features + a lot easier. SeatGeek is also in the process of building a mobile + interface that will be Backbone.js from top to bottom.
--<script> - var accounts = new Backbone.Collection; - accounts.reset(<%= @accounts.to_json %>); - var projects = new Backbone.Collection; - projects.reset(<%= @projects.to_json(:collaborators => true) %>); -</script> -+
You have to escape - </ within the JSON string, to prevent javascript injection - attacks. +
- Extending Backbone
-
- Many JavaScript libraries are meant to be insular and self-enclosed,
- where you interact with them by calling their public API, but never peek
- inside at the guts. Backbone.js is not that kind of library.
+
+ Easel is an in-browser, high fidelity web + design tool that integrates with your design and development + process. The Easel team uses CoffeeScript, Underscore.js and Backbone.js for + their rich visual editor as well as other + management functions throughout the site. The structure of Backbone allowed + the team to break the complex problem of building a visual editor into + manageable components and still move quickly.
+- Because it serves as a foundation for your application, you're meant to - extend and enhance it in the ways you see fit — the entire source - code is annotated to make this easier - for you. You'll find that there's very little there apart from core - functions, and most of those can be overriden or augmented should you find - the need. If you catch yourself adding methods to Backbone.Model.prototype, - or creating your own base subclass, don't worry — that's how things are - supposed to work. + Jolicloud is an open and independent + platform and operating system + that provides music playback, video streaming, photo browsing and + document editing — transforming low cost computers into beautiful cloud devices. + The new Jolicloud HTML5 app was built + from the ground up using Backbone and talks to the + Jolicloud Platform, which is + based on Node.js. Jolicloud works offline using the HTML5 AppCache, extends + Backbone.sync to store data in IndexedDB or localStorage, and communicates + with the Joli OS via WebSockets.
-
- How does Backbone relate to "traditional" MVC?
-
- Different implementations of the
- Model-View-Controller
- pattern tend to disagree about the definition of a controller. If it helps any, in
- Backbone, the View class can also be thought of as a
- kind of controller, dispatching events that originate from the UI, with
- the HTML template serving as the true view. We call it a View because it
- represents a logical chunk of UI, responsible for the contents of a single
- DOM element.
-
- Comparing the overall structure of Backbone to a server-side MVC framework - like Rails, the pieces line up like so: + Syllabus + is the new live blogging platform used by + The Verge + and other Vox Media sites. + Syllabus uses Backbone on both ends: an editorial dashboard and the live blog + page itself. In the back, Backbone is used to provide a + single-page experience for uploading, writing, editing and publishing content. + On the live blog, Backbone manages fetching a JSON API feed, and updating + the infinite-scrolling river of updates with new and revised content.
-
- Binding "this"
-
- Perhaps the single most common JavaScript "gotcha" is the fact that when
- you pass a function as a callback, its value for this is lost.
- When dealing with events and callbacks in Backbone,
- you'll often find it useful to rely on listenTo
- or the optional context argument that many of Underscore
- and Backbone's methods use to specify the this
- that will be used when the callback is later invoked. (See
- _.each,
- _.map, and
- object.on, to name a few).
- View events are automatically bound to
- the view's context for you.
- You may also find it helpful to use
- _.bind and
- _.bindAll
- from Underscore.js.
-
-var MessageList = Backbone.View.extend({ +++ Salon.io provides a space where photographers, + artists and designers freely arrange their visual art on virtual walls. + Salon.io runs on Rails, but does not use + much of the traditional stack, as the entire frontend is designed as a + single page web app, using Backbone.js, Brunch and + CoffeeScript. +
- initialize: function() { - var messages = this.collection; - messages.on("reset", this.render, this); - messages.on("add", this.addMessage, this); - messages.on("remove", this.removeMessage, this); ++ + + +- messsages.each(this.addMessage, this); - } +TileMill
-}); ++ Our fellow + Knight Foundation News Challenge + winners, MapBox, created an open-source + map design studio with Backbone.js: + TileMill. + TileMill lets you manage map layers based on shapefiles and rasters, and + edit their appearance directly in the browser with the + Carto styling language. + Note that the gorgeous MapBox homepage + is also a Backbone.js app. +
-// Later, in the app... ++ + + +-Inbox.messages.add(newMessage); -
- Working with Rails
-
- Backbone.js was originally extracted from
- a Rails application; getting
- your client-side (Backbone) Models to sync correctly with your server-side
- (Rails) Models is painless, but there are still a few things to be aware of.
+
+ Blossom is a lightweight project management + tool for lean teams. Backbone.js is heavily used in combination with + CoffeeScript to provide a smooth + interaction experience. The app is packaged with Brunch. + The RESTful backend is built with Flask on Google App Engine.
+- By default, Rails versions prior to 3.1 add an extra layer of wrapping - around the JSON representation of models. You can disable this wrapping - by setting: + Trello is a collaboration tool that + organizes your projects into boards. A Trello board holds many lists of + cards, which can contain checklists, files and conversations, and may be + voted on and organized with labels. Updates on the board happen in + real time. The site was built ground up using Backbone.js for all the + models, views, and routes.
--ActiveRecord::Base.include_root_in_json = false -+
- ... in your configuration. Otherwise, override - parse to pull model attributes out of the - wrapper. Similarly, Backbone PUTs and POSTs direct JSON representations - of models, where by default Rails expects namespaced attributes. You can - have your controllers filter attributes directly from params, or - you can override toJSON in Backbone to add - the extra wrapping Rails expects. + Cristi Balan and + Irina Dumitrascu created + Tzigla, a collaborative drawing + application where artists make tiles that connect to each other to + create surreal drawings. + Backbone models help organize the code, routers provide + bookmarkable deep links, + and the views are rendered with + haml.js and + Zepto. + Tzigla is written in Ruby (Rails) on the backend, and + CoffeeScript on the frontend, with + Jammit + prepackaging the static assets.
+