Last active
March 1, 2018 11:02
-
-
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.
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
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