Skip to content

Instantly share code, notes, and snippets.

@randomnerd
Created October 19, 2017 11:07
Show Gist options
  • Select an option

  • Save randomnerd/0f8ae83424e1df27e93dc0997419f5a6 to your computer and use it in GitHub Desktop.

Select an option

Save randomnerd/0f8ae83424e1df27e93dc0997419f5a6 to your computer and use it in GitHub Desktop.
import { observable, action, intercept, autorun } from 'mobx';
import createBrowserHistory from 'history/createBrowserHistory';
import Mapper from 'url-mapper';
export default class Router {
@observable location = null;
@observable route = null;
@observable match = null;
@observable values = {};
constructor(options) {
// this.params = observable.map({});
this.options = options || {
routes: {}
};
this.history = createBrowserHistory({ initialEntries: [ window.location.pathname ] });
this.mapper = Mapper();
this.history.listen(this.onLocation.bind(this));
this.onLocation(this.history.location);
autorun(() => {
if (!this.match) this.push('/');
});
}
@action onLocation(location) {
let route = this.mapper.map(location.pathname, this.options.routes);
Object.assign(this, {...route, location});
}
setValues(values) {
let location = this.mapper.stringify(this.route, values);
if (location !== this.location.pathname) this.push(location);
}
push(location) {
if (this.location && this.location.pathname === location) return;
this.history.push(location);
}
replace(location) { this.history.replace(location) }
go(n) { this.history.go(n) }
goBack() { this.history.goBack() }
goForward() { this.history.goForward() }
createHref() { return this.history.createHref(...arguments) };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment