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
http://dev.adcloud.com/blog/2012/04/16/chaplin/

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:

http://chaplinjs.org/
https://github.com/chaplinjs/chaplin

More Decks by Mathias Schäfer (molily)

Other Decks in Technology

Transcript

  1. Chaplin
    Application Architecture with Backbone.js
    AdCloud TechTalk
    April 25th, 2012
    Mathias Schäfer
    9elements

    View Slide

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

    View Slide

  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

    View Slide

  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

    View Slide

  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…)

    View Slide

  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

    View Slide

  7. Backbone Classes
    A Quick Overview
    Backbone.Events
    Backbone.Model
    Backbone.Collection
    Backbone.View
    Backbone.History
    Backbone.Router

    View Slide

  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

    View Slide

  9. Backbone.Model
    Fetching, processing and storing data
    Key feature: the attributes hash
    Changes will fire change events
    Standard sync via RESTful HTTP

    View Slide

  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') );

    View Slide

  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

    View Slide

  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();

    View Slide

  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

    View Slide

  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();

    View Slide

  15. Model
    Storage
    View Template
    DOM
    observes and
    modifies
    creates and
    handles input
    queries and
    syncs with
    renders
    Router creates

    View Slide

  16. Applications on Top of
    Backbone

    View Slide

  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”

    View Slide

  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

    View Slide

  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

    View Slide

  20. https://github.com/moviepilot/chaplin

    View Slide

  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

    View Slide

  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

    View Slide

  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)

    View Slide

  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

    View Slide

  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

    View Slide

  26. Mediator
    SomeController
    ApplicationController
    Router
    SomeView
    ApplicationView
    SomeModel
    Application

    View Slide

  27. Mediator
    SomeController
    ApplicationController
    Router
    SomeView
    ApplicationView
    SomeModel
    Application

    View Slide

  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

    View Slide

  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

    View Slide

  30. Questions? Ideas?
    Opinions?
    I’m molily on Twitter & Github
    [email protected]
    github.com/moviepilot/chaplin
    9elements.com
    Fork
    m
    e
    on
    G
    ithub!

    View Slide