Skip to content

Instantly share code, notes, and snippets.

@nragaz
Created January 16, 2011 23:43
Show Gist options
  • Save nragaz/782275 to your computer and use it in GitHub Desktop.
Save nragaz/782275 to your computer and use it in GitHub Desktop.
Add callbacks to remote links in Rails to manage browser history using pageState and replaceState
function historySupport() {
return !!(window.history && window.history.pushState !== undefined);
}
function pushPageState(state, title, href) {
if (historySupport()) {
history.pushState(state, title, href);
}
}
function replacePageState(state, title, href) {
if (state == undefined) { state = null; }
if (historySupport()) {
history.replaceState(state, title, href);
}
}
$(function() {
window.onpopstate = function(e) {
if ($('body').attr('data-state-href') === location.href) {
return false;
}
if (e.state !== null) {
// do something with your state object
}
$.ajax({
url: location.href,
dataType: 'script',
success: function(data, status, xhr) {
$('body').trigger('ajax:success');
},
error: function(xhr, status, error) {
// You may want to do something else depending on the stored state
alert('Failed to load ' + location.href);
},
complete: function(xhr, status) {
$('body').attr('data-state-href', location.href);
}
});
};
var getA = 'a[data-remote][data-method!="put"][data-method!="post"][data-method!="delete"]'
, getForm = 'form[data-remote][method="get"]';
function getState(el) {
// insert your own code here to extract a relevant state object from an <a> or <form> tag
// for example, if you rely on any other custom "data-" attributes to determine the link behaviour
return {};
};
$('body').attr('data-state-href', location.href);
$(getA).
live('ajax:beforeSend', function(xhr) {
pushPageState(getState(this), "Loading...", this.href);
window.title = "Loading...";
});
$(getForm).
live('ajax:beforeSend', function(xhr) {
var href = $(this).attr("action") + "?" + $(this).serialize();
pushPageState(getState(this), 'Loading...', href);
window.title = "Loading...";
});
$(getA + ',' + getForm).
live('ajax:complete', function(xhr) {
$('body').attr('data-state-href', location.href);
replacePageState(getState(this), window.title, location.href);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment