Skip to content

Instantly share code, notes, and snippets.

@erikeldridge
Created July 18, 2012 05:37
Show Gist options
  • Save erikeldridge/3134411 to your computer and use it in GitHub Desktop.
Save erikeldridge/3134411 to your computer and use it in GitHub Desktop.
pushState routing boilerplate
<!DOCTYPE html>
<html>
<body>
<a href="/edit/1" class="js-nav">edit</a><br/>
<a href="/1" class="js-nav">1</a><br/>
<a href="/" class="js-nav">default</a><br/>
<a href="#" class="create">create</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
var views = {};
views.edit = function(){
console.log('rendering edit view');
};
views.default = function(){
console.log('rendering default view');
};
views.timeline = function(){
console.log('rendering timeline view');
};
// nav routing
function route(path, push){
if(false !== push){
window.history.pushState(null, null, path);
}
var view = 'default';
if(/\/edit\/\d+/.test(path)){
view = 'edit';
}else if(/\/\d+/.test(path)){
view = 'timeline';
}
console.log('routing to', view);
views[view]();
}
$('a.js-nav').click(function(){
route(this.href);
return false;
});
// back-button and page load routing
window.addEventListener("popstate", function(e) {
console.log('popping state', document.location.pathname);
route(document.location.pathname, false);
});
// route after action
$('.create').click(function(){
console.log('creating new record ...');
var id = 1;
route('/'+id);
return false;
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment