Swizec Teller - a geek with a hatswizec.com

    Writing modular Backbone with Backbone.SubRoute

    Working on a complicated frontend web app, Backbone soon becomes unwieldy. Routes definitions grow and grow, views steal each other's actions and parts of the code try to become independent modules.

    This is the problem I faced a few weeks ago while working on the fanciest signup funnel I ever helped create. Visitors would see the splash page, create their cart, revise it, sign up, add billing and shipping info, and finally checkout without ever refreshing the page.

    A daunting challenge only made worse by the complexity of components involved. We needed a full-blown inventory listing, a full-blown cart editor and we even added some shiny bits to the billing and shipping forms. The funnel changes into an accordion after the first step.

    Oh and the user can refresh at any point in the funnel without losing their place.

    To divide work among the team, we took a straight-forward modular approach: a module handles the whole funnel, submodules take care of each step. This way everyone can focus on their own piece of the funnel and the javascript code can be reused when making the standalone versions of each step for signed-in users.

    The skeleton

    Backbone.SubRoute makes this approach possible by letting you create Backbone routers attached at a certain path in the URL. By doing something like var bla = new SubBla("/bla", …) you create a self-contained Backbone app that handles everything under /bla and doesn't care about the outside world.

    We didn't like how the official docs recommend going about this, so we made it automagical-er.

    A simple app_skeleton.js file holds the entire application together and loads modules when they're needed.

    var YourApp = (window.YourApp = { Routers: {} });
    YourApp.Router = Backbone.Router.extend({
    routes: {
    "": "invokeRootModule",
    ":module(/*subroute)": "invokeModule",
    invokeRootModule: function () {
    invokeModule: function (module, subroute) {
    module = module.toLowerCase().capitalize();
    if (!YourApp.Routers[module]) {
    YourApp.Routers[module] = new YourApp[
    ].Router(module.toLowerCase() + "/", { createTrailingSlashRoutes: true });

    We agree to register all our modules as window.YourApp.Module.Router. This lets us put every module in its own file and creates a predictable interface for creating instances of sub routers.

    That was easy, now all we need is a submodule.

    A module

    Modules work the same as standalone Backbone applications. They have views and collections and models and everything is held together by a router. You just have to conform to what app skeleton expects.

    A simple module might look like this:

    (function ($) {
    YourApp.Root = {};
    YourApp.Root.Router = Backbone.SubRoute.extend({
    routes: {
    "(:step)": "step",
    initialize: function () {
    // do stuff
    step: function () {
    // something for this step

    Router is the only necessary part. Everything else is added to taste. We rely on the router's initialize function as the entry point into the module, so all initialization should happen in there.

    Sub sub modules

    Let's make things interesting; the module is called Root because it's going to handle submodules of its own - funnel steps in our case. Root loads them on the home page, app_skeleton loads them on standalone pages.

    For some reason dynamically instantiating submodules was not an option in this case. Not sure why, but it probably had to do with listening to events between submodules. Yes, unclean, but there's no reason to go overboard with architecture principles. Sometimes you just have to get shit done.

    Root's initialize becomes something like this:

    initialize: function () {
    this.subrouters = {};
    this.subrouters.step1 = new YourApp.Step1.Router("base/step1/");
    this.subrouters.step2 = new YourApp.Step2.Router("base/step2/");
    // ...
    // other stuff

    Every subrouter is instantiated on initialize. If we want to change our views when particular submodules are active, we have to listen to their route events because they steal routing from their parent. For instance, we had to make sure the accordion was visible, splash step was hidden and so on.

    __listenToSubrouters: function () {
    _.keys(this.subrouters).map(_.bind(function (router) {
    _.bind(function () {
    this.step(router, "",
    {dont_navigate: true});
    }, this));
    }, this));

    __listenToSubrouters goes through all the instantiated routers and makes sure to call the step function when a submodule does something.

    The step function becomes something like this:

    step: function(step, subpath, options) {
    // do view stuff here
    subpath = subpath || "";
    if (this.subrouters[step] && !(options && options.dont_navigate)) {
    this.subrouters[step].navigate(subpath, {trigger: true});

    This makes sure to .navigate subrouters when it's appropriate and avoid doing so when the code is reacting to a subrouter's route event. I've left out the view stuff because that isn't very interesting.


    And there you go. Backbone with a modular design that keeps modules neat, encapsulated and reusable.

    To make things even smoother I also added an event that triggers only when a certain step is fully visible. This helps submodules activate/deactivate their views properly because things like jQuery Waypoints don't initialize well when elements aren't at their final positions.

    As for the super fancy signup process - you'll be able to see it when Dwellers launches. It's pretty great.

    Enhanced by Zemanta

    Did you enjoy this article?

    Published on July 31st, 2013 in JavaScript, jQuery, Modules, Programming, Router, Uncategorized, Web application

    Learned something new?
    Want to become an expert?

    Here's how it works 👇

    Leave your email and I'll send you thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

    Join Swizec's Newsletter

    And get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career. Real lessons from building production software. No bullshit.

    "Man, love your simple writing! Yours is the only newsletter I open and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"

    ~ Ashish Kumar

    Join over 14,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

    Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

    Ready to Stop copy pasting D3 examples and create data visualizations of your own?  Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

    Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

    Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

    Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

    By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️

    Created bySwizecwith ❤️