Last active
August 10, 2018 09:03
-
-
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…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
<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> | |
... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}); | |
} | |
}); | |
} | |
}); |
Thanks it's work but if you refresh page you will get the 404
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
add at line 17 var bbRootRegexp = new RegExp(bbRoot)