Created
October 17, 2013 15:43
-
-
Save cybrown/7027249 to your computer and use it in GitHub Desktop.
Javascript prototype to manage history via hash.
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
function HistoryHandler(pathname) { | |
this.hashes = []; | |
this.active = false; | |
var self = this; | |
this.pageregex = new RegExp(pathname.replace(/\//g, '\\/') + '$'); | |
if (window.location.pathname.match(this.pageregex)) { | |
this.active = true; | |
$(window).on('hashchange', function (event) { | |
for (var i in self.hashes) { | |
var h = self.hashes[i]; | |
if (typeof h.hash == 'string' && h.hash == window.location.hash) { | |
h.action(); | |
break; | |
} else if (h.hash instanceof RegExp) { | |
var params = window.location.hash.match(h.hash); | |
if (!params) { | |
continue; | |
} | |
params.shift(); | |
if (window.location.hash.match(h.hash)) { | |
h.action.apply(this, params); | |
break; | |
} | |
} | |
} | |
}); | |
} | |
}; | |
HistoryHandler.prototype.on = function (hash, cb) { | |
if (!this.active) { | |
return this; | |
} | |
if (typeof hash == 'string') { | |
this.hashes.push({ | |
hash: hash === '' ? '' : '#' + hash, | |
action: cb | |
}); | |
} else { | |
this.hashes.push({ | |
hash: new RegExp('^#' + hash.source + '$'), | |
action: cb | |
}); | |
} | |
return this; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment