I want to check if every time the URL has changed, I'd fire an event. Since, there's no pushstate event I'm following this advice How to get notified about changes of the history via history.pushState?
(function(history) {
var pushState = history.pushState;
history.pushState = function(state) {
if (typeof history.onpushstate == "function") {
history.onpushstate({
state: state
});
}
return pushState.apply(history, arguments);
}
function e(event) {
console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
}
window.addEventListener('popstate', e);
history.onpushstate = e;
})(window.history)
However, my lib allows mutliple instances. If I initialize my library multiple times, I'd get messages according to how many times the the library has been initialized. Is there anyway I can make sure that only one event is attached even though I run that snippet multiple times?