Single Page Interface using Backbone

Here’s a little snippet that contains the bare basics of a single page interface built in backbone.

var AppRouter = this.Backbone.Router.extend({
 routes: {
 “*actions”: “defaultRoute”
 }
});
var app_router = new AppRouter();

This creates a Backbone Router. When this router receives a “navigate” command, it in turn triggers the “route:defaultRoute” event.

app_router.on(‘route:defaultRoute’, function (actions) {
 var contentcontainer = $(‘#body .main-content’);
 contentcontainer.html(‘Loading…’);
 $.get(‘/’ + actions).then(function (data) {
 contentcontainer.html(‘

ajax loaded:

‘ + data);
 }, function (data) {
 contentcontainer.html(‘An error occurred: ‘ + data);
 });
});

Now, when the defaultRoute is triggered, the url it is navigating towards is retrieved via ajax and then inserted in the contentcontainer.

this.Backbone.history.start({
 pushState: true,
 root: “/”,
 silent: true
});

To keep the history and url’s working, we initiate the Backbone history, with pushState.

$(function () {
 $(‘body’).on(‘click’, ‘a’, function (evt) {
 evt.preventDefault();
 app_router.navigate($(this).attr(‘href’), {
 trigger: true
 });
 });
});

And then to tie things together: on each link in the page, prevent the default action and trigger the routing.

On the server you can see if the request is AJAX or not. If it is, don’t return the header and footer, just the contents of the main-content element. If it’s not and AJAX call, then serve the entire page. This way the entire site works like a single page interface, but when you reload the page it’ll work too.

This is especially neat because search engines often don’t use javascript the same way your typical user does. Using the above approach makes the website navigable without javascript.

Best of all, it’s extensible! Want a specific pagetransition to animate? No problem, create a route for it and handle that specific transition.

Enjoy!


Check out our Engineering Blog for more in-depth articles on pragmatic code for happy users!