I wrote a small hash change object, it will alert the url hash whenever it changes:
(function() {
function hashChange() {
this.previousHash;
this.initialize();
}
hashChange.prototype.initialize = function() {
this.setInterval = window.setInterval(this.checkHashChange, 0);
}
hasChange.prototype.uponHashChange = function(hash) {
alert('I executed!');
var hashValue = hash.split('#')[1];
alert(hashValue);
}
hashChange.prototype.checkHashChange = function() {
var hash = window.location.hash;
if(hash && hash !== this.previousHash) {
this.previousHash = hash;
this.uponHashChange(hash); // <---- doesn't execute
}
}
var hashChange = new hashChange();
})();
But this:
this.uponHashChange(hash);
Never gets executed. Why?
This line is not going to do exactly what you mean.
this.checkHashChangewill lose its binding to its currentthis(which would be ahashChangeinstance), and will instead be invoked in the context of thewindowobject.You need to bind it explicitly to the correct context object:
Matt Greer has suggested
Function.bind, which would make it more concise and likely more readable:Unfortunately,
Function.bindis not yet widely supported across browsers.