Reducing Backbone Routers To Nothing More Than Configuration
I received an email from someone who was looking through my BBCloneMail and Backbone.Marionette source code. One of the comments they made talked about how my router callback methods were nothing more than pass-throughs, calling out to another object. (I think this is one of the points that Tim Branyen was making in the comments of my previous post, too).
Here’s an example of the code that the email was referring to:
The emailer suggested that I factor out the boilerplate code and set up some custom functionality to go straight from the route definition to a method call on another object, In other words, instead of having to implement a callback method on the router itself, having the callback method be on another object.
Removing The Callback Functions
I like the idea so I hacked together a working version directly in to the BBCloneMail application. The result is that my router went from the code above, to this:
Now my router is nothing more than configuration! There are no callback methods directly in the router anymore. The callbacks that I defined are located on another object, instead.
To make this work, my “AppRouter” expects to receive an “app” object when it’s instantiated. This is the object that contains the callback methods I specified.
All of the parameters that you define in the route are forwarded to your app object’s callback method. So, when the empty (“”) route fires, the “showInbox” method on the “BBCloneMail.MailApp” object will be called with no parameters. And when “inbox/:id” fires, the “showMessage” method on “BBCloneMail.MailApp” will receive a single parameter with the id from the route.
The AppRouter Code
Here’s the code that I put in to my AppRouter, to make this work:
This code doesn’t preclude you from using the standard “routes” and callbacks, either. You can mix and match the standard routes and the appRoutes however you want. The routes defined in appRoutes get processed after the standard routes, though. This means it’s possible for an appRoute to override a normal route.
Still Needs Work
You can see it live in my BBCloneMail app right now. It may not stay there for long, though, as I’m constantly changing that code. Also – I haven’t thoroughly tested this so there may be some browser compatibility issues that I haven’t run into yet… or some other issues that I don’t know about. I’m going to keep playing with this idea and once I get it to something I really like, I’ll re-write it (test-first of course) into Backbone.Marionette.
I’m also looking for feedback on this. I realize there are some limitations to this, and there are probably some dumb thing I’ve done, too. If anyone has any suggestions for how to improve this, I’d love to hear it.