Question

I am building an application in backbone combining the modular and facade/mediator pub/sub patterns from https://github.com/addyosmani/backbone-aura/ to send messages between modules in order to keep a clean codebase.

Grepping for Router in the entire app example for aura, I found only the readme file describing the ideal use of routers being part of modules themselves: "In Backbone.js terms, widgets are composed of Models, Views, Collections and Routers as well as any templates needed for the widget to rendered."

So I tried a number of solutions to implement a scalable routing system (scalable meaning modules can specify their own subroutes), including a router module that accepts message set-route to set the route, and modules that listen to the route message. I've also used a sub-router per module. The problem seems that on initial page loads, because of the 'async' nature of messaging, the routes and their callbacks may not be defined by the time the global router parses the URL. You can imagine I maybe need to queue all messages before starting the router module.

I want to implement something clean and that makes sense. I was also thinking about potentially parsing all routes of all widgets first, then instantiating the router, which makes the router module a special case, and thus, shouldn't be a part of the modules.

Should the Router be a module that uses messages, or should it be an extension, or some higher order piece of the architecture that is global that modules do have access to?

I know this is a loaded question, thanks in advance for any help!

Was it helpful?

Solution

There's been a lot of debate over this issue, and I think a lot of that stemmed from what I think was confusion over Router formally being called Controller. By the time I started using Backbone late last year, the change was already made, but I believe lots of people had already built applications around the router being a controller. I never agreed with that. To me - relying on experience of having built a proprietary MVC engine similar to Backbone long before Backbone was created - a router was simply a history manager component.

So to address your particular issue on deciding how best to implement a router, take into consideration a few things:

  1. First of all, a router is not a necessary component of an application. You could do without a router and still navigate to the various pages or screens of the app.
  2. A router is not a controller in that its primary function is to manage history. Though you could embed application business logic within a router, I've always found that that muddies the waters of what a router really does.
  3. By making a router a component of an application, you create a better separation of concerns, and can have a much more effective pub/sub type of arrangement.

Below is code for a router module I use in my apps that follows the mediator, pub/sub patterns:

/**
 * The idea behind this component is simply to relegate Backbone.Router to
 * doing what it does best: History Management. All it is responsible for
 * is two things:
 *
 * 1. Update the URL if router.navigate is invoked
 * 2. Trigger a routeChanged event if the URL was updated either by a bookmark or
 *    typed in by a user.
 */
define(function () {
    return Backbone.Router.extend({
        initialize : function (map) {
            this._reversedMap = this.reverseModuleMap(map);
        },
        routes:{
            '*actions':'notify'
        },
        notify:function (actions) {
            var args = arguments;
            this.trigger("routeChanged", {command:actions});
        },
        /**
         * Override Backbone.Router.navigate. Default is to pass a router fragment, but for
         * our uses, we'll translate the "route" into a module mapping so that the controller
         * will know which module to display.
         * @param param
         * @param options
         */
        navigate:function (param, options) {
            //console.log('navigate', param);
            if(!param.suppressNavigate && param.actionCommand)  {
                Backbone.Router.prototype.navigate.call(this, this._reversedMap[param.actionCommand]);
            } else if(!param.actionCommand) {
                Backbone.Router.prototype.navigate.call(this, param, options);
            }
        },
        /**
         * this function simply reverses the key and value of the "map"
          * @param map
         */
        reverseModuleMap:function (map) {
            var newMap = {};
            _.each(map, function (value, key) {
                newMap[value] = key;
            });
            // reversed key and value
            return newMap;
        }
    });
});

Then when I instantiate the component, I pass it a map so that my controller knows what module to navigate to:

this._router = new Router({
    _default: 'moduleA',
    sites : 'moduleA',
    apps : 'moduleB'
});
this._router.on('routeChanged', this.handleRouteChange, this);

The most important thing I've found with this is that it keeps the code nice and simple, and allows me to focus on business logic in my controllers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top