Skip to content

Instantly share code, notes, and snippets.

@cybrown
Created October 17, 2013 15:43
Show Gist options
  • Save cybrown/7027249 to your computer and use it in GitHub Desktop.
Save cybrown/7027249 to your computer and use it in GitHub Desktop.
Javascript prototype to manage history via hash.
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