Skip to content

Instantly share code, notes, and snippets.

@kandadaboggu
Last active March 1, 2018 11:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kandadaboggu/4638701 to your computer and use it in GitHub Desktop.
Save kandadaboggu/4638701 to your computer and use it in GitHub Desktop.
The `History.js` triggers `statechange` event for `pushState` and `replaceState` API calls. There is no way to distinguish between Back button events and API generated events. The dev branch of the library has fixed this issue. I wanted a simple fix until the fix is public. This is my attempt.
if (History && History.enabled) {
// START OF WRAPPER SECTION
var HistoryWrapper = {
apiEventInProgress: false,
isBrowserEvent: function () {
return !this.apiEventInProgress;
},
getState: function () {
return History.getState();
},
silentExecute: function(f, data, title, url) {
this.apiEventInProgress = true;
var reply = f(data, title, url);
this.apiEventInProgress = false;
return reply;
},
pushState: function(data, title, url) {
return this.silentExecute(History.pushState, data, title, url);
},
replaceState: function(data, title, url) {
return this.silentExecute(History.replaceState, data, title, url);
},
onPopState: function(f) {
var wrapper = this;
History.Adapter.bind(window, 'statechange', function() {
if (wrapper.isBrowserEvent()) {
f();
}
});
}
};
// END OF WRAPPER SECTION
// Usage section
// register onPopState callback
HistoryWrapper.onPopState(function() {
state = HistoryWrapper.getState();
data = state.data;
if ( data && (data.name == "foo-bar") ) {
$.getScript(state.url);
}
});
// push/replace
HistoryWrapper.pushState({ name: "foo-bar"}, document.title, url));
HistoryWrapper.replaceState({ name: "foo-bar"}, document.title, url + "?page=2"));
HistoryWrapper.pushState({ name: "foo-bar"}, document.title, url + "&sort=name"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment