Skip to content

Instantly share code, notes, and snippets.

@ssafejava
Last active December 17, 2015 03:39
Show Gist options
  • Save ssafejava/5544757 to your computer and use it in GitHub Desktop.
Save ssafejava/5544757 to your computer and use it in GitHub Desktop.
Main.js with anchor link parsing
require([
'app',
'backbone',
// Application Router
'routers/ApplicationRouter'
],
function(app, Backbone, ApplicationRouter) {
// Define your master router on the application namespace and trigger all
// navigation from this instance.
app.router = new ApplicationRouter();
// Trigger the initial route and enable HTML5 History API support, set the
// root folder to '/' by default. Change in app.js.
Backbone.history.start({ pushState: true, root: app.root });
// All navigation that is relative should be passed through the navigate
// method, to be processed by the router. If the link has a `data-bypass`
// attribute, bypass the delegation completely.
$(document).on('click', 'a[href]:not([data-bypass])', function(evt) {
// Get the absolute anchor href.
var href = $(this).prop('href');
// Get the absolute root.
var root = location.protocol + '//' + location.host + app.root;
var route = href.split(root)[1];
// Ensure the root is part of the anchor href, meaning it's relative.
if (href.slice(0, root.length) === root) {
// Stop the default event to ensure the link will not cause a page
// refresh.
evt.preventDefault();
// `Backbone.history.navigate` is sufficient for all Routers and will
// trigger the correct events. The Router's internal `navigate` method
// calls this anyways. The fragment is sliced from the root.
Backbone.history.navigate(route, {trigger: true});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment