Backbone.js has routes. Hooray, now ‘#here’ can go here, ‘#there’ can go there, and so on! That’s the logic side sorted out.
What about presentation?
In many cases, 1 route <=> 1 ‘page’ of content.
How do we do that?
The Bootstrap library has a tabs component that implements a couple of very useful things:
- Provides a link between a menu and a set of ‘pages’
- Easy to trigger page changes
We still need to add two small things to connect any router to a set of pages:
- When a route is triggered, activate a matching tab.
- When a tab is activated, trigger any matching route.
All it needs is the following code:
//On click, show the page, allow to route. $('#tab_demo_menu a').on('click', function (e) { $(this).tab('show'); } //On route, trigger the 'click' Backbone.history.on('route', function(router, event) { $('#tab_demo_menu a[href="#'+this.fragment+'"]').click(); });
So what does this mean?
- No modification needs to be made to the router.
- As long as a tab with that route name exists, it will automatically be shown when the route is invoked.
- A route with no corresponding tab can be invoked with no ill effects; maybe you want to show a dialog above whatever page is active?
- You can link to a particular tab with the #fragment; something that Bootstrap tabs don’t support by default.
Look! A finely crafted demo: https://mindbleach.com/demos/backbone_bootstrap_pages/