Skip to content

Instantly share code, notes, and snippets.

@colllin
Last active August 10, 2018 09:03
Show Gist options
  • Save colllin/5717284 to your computer and use it in GitHub Desktop.
Save colllin/5717284 to your computer and use it in GitHub Desktop.
Automatic Backbone Routing - automatically capture links with relative URLs and route them through your Backbone Router. This method does not break any fallback server-side routing, because you're still using real URLs, i.e. `<a href="/my/app/page/4">See?</a>`. If a link can't be handled by any of your routers, it will fall through so the browse…
...
<nav>
<ul>
<li>
<a href="/my/app">Home</a>
</li><li>
<a href="/my/app/posts">Posts</a>
</li><li>
<a href="/my/app/posts/1">The First Post</a>
</li>
</ul>
</nav>
...
MyRouter = Backbone.Router.extend({
routes: {
'posts/:post_id': 'showPost',
'posts': 'indexPosts',
'': 'home'
},
...
});
myRouter = new MyRouter();
// start Backbone.history - root is optional
Backbone.history.start({pushState: true, root: 'my/app'});
// save the root for slight performance improvement
var bbRoot = Backbone.history.root.replace(/^\//, '').replace(/\/$/, '');
// on every click, check if it's an href that can be handled by the router
$(document.body).on('click', 'a', function(event) {
// clean leading/trailing slashes
var href = $(this).attr('href').replace(/^\/+/, '').replace(/\/+$/, '');
// only handle click if href contains backbone history root
if (bbRootRegexp.test(href)) {
href = href.replace(bbRootRegexp, '').replace(/^\/+/, '').replace(/\/+$/, '');
_(Backbone.history.handlers).chain().pluck('route').each(function(route) {
if (route.test(href)) {
event.preventDefault();
Backbone.history.navigate(href, {trigger: true});
}
});
}
});
@GlebDolzhikov
Copy link

add at line 17 var bbRootRegexp = new RegExp(bbRoot)

@GlebDolzhikov
Copy link

Thanks it's work but if you refresh page you will get the 404

@GlebDolzhikov
Copy link

I found ! For apache server just add in .htaccess

RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !index RewriteRule (.*) index.html [L,QSA]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment