Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Chaplin: JavaScript Application Architecture with Backbone.js (AdCloud TechTalk)

Chaplin: JavaScript Application Architecture with Backbone.js (AdCloud TechTalk)

AdCloud TechTalk, 2012-04-25, Cologne, Germany

Backbone.js is a small JavaScript library which helps building JavaScript-driven web applications. It’s widely used by companies like LinkedIn, Groupon, Foursquare and 37Signals. While Backbone.js is a good starting point, it is quite limited and does not provide a top-level architecture for scalable Web applications.

Chaplin.js is an architecture for JavaScript applications using the Backbone.js library. It provides a lightweight and flexible structure that features well-proven design patterns and best practices:



  1. Chaplin Application Architecture with Backbone.js AdCloud TechTalk April 25th, 2012

    Mathias Schäfer 9elements
  2. Hello! Mathias Schäfer (molily) molily.de Software developer Client-side JavaScript expert

  3. JavaScript Applications Backend communication OOP & Functional Programming Application Architecture

    Routing & History DOM Scripting HTML Templating Data Binding Modularization & Dependency Mgmt. Building & Packaging Unit and Functional Tests Coding Guidelines and Lints Documentation
  4. Every JavaScript application is a beautiful flower That is, JavaScript

    application development is a mess You’ve got plenty of options Few conventions and standards Every library has its own interpretation of patterns like MVC If you choose a development stack, you’re trapped
  5. Introducing Backbone.js backbonejs.org A simple and small library Popular and

    field-tested Actively developed Well-tested and readable code Free and open source Typically used with Underscore, jQuery and a templating engine (_.template, Mustache, Handlebars…)
  6. What Backbone.js can do for you Basically two ideas: Models

    fetch, process and store the raw data, Views render data and provide a user interface Routers/History save and restore application state using the URL
  7. Backbone Classes A Quick Overview Backbone.Events Backbone.Model Backbone.Collection Backbone.View Backbone.History

  8. Backbone.Events Basis for an event-driven architecture Register event handlers and

    dispatch events Methods: on, off, trigger Backbone’s key feature Included by all other Backbone classes
  9. Backbone.Model Fetching, processing and storing data Key feature: the attributes

    hash Changes will fire change events Standard sync via RESTful HTTP
  10. var Car = Backbone.Model.extend(); var car = new Car({ name:

    'DeLorean DMC-12', manufactured: 1981 }); alert( car.get('name') ); car.set({ manufactured: 1982 }); alert( car.get('manufactured') );
  11. Backbone.View Holds a DOM element and renders the model data

    Knows about its model or collection Handles DOM events (user input) Observes model events (binding) Invokes model methods or triggers events
  12. var CarView = Backbone.View.extend({ initialize: function () { this.model.on('change', this.render,

    this); }, render: function () { this.$el.html('Name: ' + this.model.get('name')); } }); var carView = new CarView({ model: car, el: $('#car') }); carView.render();
  13. Backbone.Router and Backbone.History A Router maps URLs to its methods

    History is the actual workhorse, observes URL changes and fires callbacks HTML5 History with Hash URI fallback Routers usually create models and views
  14. var CarRouter = Backbone.Router.extend({ routes: { "cars": "index", "cars/:id": "show"

    }, index: function () { var cars = new CarCollection(); var carsView = new CarsView({ collection: cars }).render(); cars.fetch(); }, show: function (id) { var car = new Car({ id: id }); var carView = new CarView({ model: car }).render(); car.fetch(); } }); var carRouter = new CarRouter(); Backbone.history.start();
  15. Model Storage View Template DOM observes and modifies creates and

    handles input queries and syncs with renders Router creates
  16. Applications on Top of Backbone

  17. Backbone is just the beginning Minimalistic by intent Not a

    full-fledged solution No top-level patterns to structure an application. Not MVC, MVP or MVVM. No right answer by design, few conventions “There’s more than one way to do it”
  18. Backbone just points in the right direction “There’s incredibly little

    prescription about how to use the tools that Backbone provides, … the code I wrote … looks a lot different than what someone else might come up with. … [It’s] important to take [Backbone] for what it is: an uber-tiny library that gets you pointed in the right direction. What I really want to see are fuller-fledged frameworks that build on top of Backbone, because I think there’s a lot more that can be standardized beyond what Backbone offers.” – Rebecca Murphey, http://bit.ly/wdgCdn
  19. Abstraction Layers for Backbone Marionette https://github.com/derickbailey/backbone.marionette Thorax https://github.com/walmartlabs/thorax Layoutmanager https://github.com/tbranyen/backbone.layoutmanager

    Aura https://github.com/addyosmani/backbone-aura
  20. https://github.com/moviepilot/chaplin

  21. Meet Chaplin An application architecture on top of Backbone.js Derived

    from moviepilot.com, a real-world single- page application Current state: An example application In development: An external library + examples Free and open source https://github.com/moviepilot/chaplin
  22. Step 1/6 Enforce conventions and write readable code Define how

    and where to create models/views, fetch data, render views, subscribe to events, clean up etc. Extend the core classes of Backbone (Model, Collection, View) CoffeeScript class hierarchies with super calls as well as object composition CollectionView for rendering collections automatically
  23. Step 2/6 Loosely-couple Modules for a scalable architecture Module encapsulation,

    dependency management and packaging via RequireJS (AMD) Event-driven architecture: Cross-module communication using the Publish/Subscribe pattern Share information using Mediator object(s)
  24. Step 3/6 Separate routing and the code which creates a

    screen Backbone.Router makes it hard to track application- wide state and transition between screens Separate routing and the code which creates the models and views Introduce Controllers and reinvent the Router A controller represents a screen of the application
  25. Step 4/6 Manage top-level state (Chaplin’s development branch) Application creates

    core controllers ApplicationController creates and removes controllers tracks the current application state ApplicationView top-level view manager shows and hides the main views
  26. Mediator SomeController ApplicationController Router SomeView ApplicationView SomeModel Application

  27. Mediator SomeController ApplicationController Router SomeView ApplicationView SomeModel Application

  28. Step 5/6 Memory Management Event handling creates references between objects,

    you need to remove them so the Garbage Collector can remove the objects Strict memory management and standardized object disposal All classes provide a dispose destructor which are called automicatically An event handling abstration layer which allow for automatic disposal
  29. Step 6/6 Handling asynchronous dependencies Backbone’s own event handling, wrapped

    Publish/Subscribe all over Model and collection synchronization: Mix in jQuery Deferreds More complex state machines (SyncMachine) Wrap functions to wait for Deferreds
  30. Questions? Ideas? Opinions? I’m molily on Twitter & Github mathias.schaefer@9elements.com

    github.com/moviepilot/chaplin 9elements.com Fork m e on G ithub!