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?
-
3checkHashChange will run in the context of the global object. You need something like Function.bind.Matt Greer– Matt Greer2012年10月04日 19:16:13 +00:00Commented Oct 4, 2012 at 19:16
1 Answer 1
this.setInterval = window.setInterval(this.checkHashChange, 0);
This line is not going to do exactly what you mean. this.checkHashChange will lose its binding to its current this (which would be a hashChange instance), and will instead be invoked in the context of the window object.
You need to bind it explicitly to the correct context object:
var self = this;
this.setInterval = window.setInterval(function() { self.checkHashChange() }, 0);
Matt Greer has suggested Function.bind, which would make it more concise and likely more readable:
this.setInterval = window.setInterval(checkHashChange.bind(this), 0);
Unfortunately, Function.bind is not yet widely supported across browsers.
3 Comments
uponHashChange invocation at all.