Skip to content

Instantly share code, notes, and snippets.

@bgrins
Created May 1, 2013 15:00
Show Gist options
  • Save bgrins/5495779 to your computer and use it in GitHub Desktop.
Save bgrins/5495779 to your computer and use it in GitHub Desktop.
Wrap pushState and popState into a helper function that feature detects and fires callbacks http://jsbin.com/olabac/3/edit
var State = (function() {
var supported = !!window.history;
var enabled = true;
var popCallbacks = [];
var pushCallbacks = [];
var initialURL = location.href;
function triggerPopStates(state) {
popCallbacks.forEach(function(c) {
c(state);
});
}
function triggerPushStates(state, title, href) {
pushCallbacks.forEach(function(c) {
c(state, title, href);
});
}
if (supported) {
// Initially replace a state. This allows a popState event to fire when going back to initial state
history.replaceState({}, document.title, window.location.href);
window.addEventListener("popstate", function(e) {
var state = e.state;
if (state) {
triggerPopStates(state);
}
}, false);
}
return {
enabled: enabled,
disable: function() {
enabled = false;
},
enable: function() {
enabled = true;
},
pushState: function(state, title, href) {
if (!supported || !enabled) {
return;
}
history.pushState(state, title, href);
triggerPushStates(state, title, href);
},
onPopState: function(f) {
if (!supported || !enabled) {
return;
}
popCallbacks.push(f);
},
onPushState: function(f) {
if (!supported || !enabled) {
return;
}
pushCallbacks.push(f);
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment