react-router-component
Version:
Declarative router component for React
54 lines (42 loc) • 1.39 kB
JavaScript
;
var Environment = require('./Environment');
/**
* Routing environment which routes by `location.hash`.
*/
function HashEnvironment() {
this.onHashChange = this.onHashChange.bind(this);
Environment.call(this);
}
HashEnvironment.prototype = Object.create(Environment.prototype);
HashEnvironment.prototype.constructor = HashEnvironment;
HashEnvironment.prototype.getPath = function() {
return window.location.hash.slice(1) || '/';
};
HashEnvironment.prototype.pushState = function(path, navigation) {
window.location.hash = path;
};
HashEnvironment.prototype.replaceState = function(path, navigation) {
var href = window.location.href.replace(/(javascript:|#).*$/, '');
window.location.replace(href + '#' + path);
};
HashEnvironment.prototype.start = function() {
if (window.addEventListener) {
window.addEventListener('hashchange', this.onHashChange);
} else {
window.attachEvent('onhashchange', this.onHashChange);
}
};
HashEnvironment.prototype.stop = function() {
if (window.removeEventListener) {
window.removeEventListener('hashchange', this.onHashChange);
} else {
window.detachEvent('onhashchange', this.onHashChange);
}
};
HashEnvironment.prototype.onHashChange = function() {
var path = this.getPath();
if (this.path !== path) {
this.setPath(path, {isPopState: true});
}
};
module.exports = HashEnvironment;