Skip to content

Instantly share code, notes, and snippets.

@kristian76
Created May 18, 2016 05:20
Show Gist options
  • Save kristian76/91705f0d56bb3da719e5868a17d372d4 to your computer and use it in GitHub Desktop.
Save kristian76/91705f0d56bb3da719e5868a17d372d4 to your computer and use it in GitHub Desktop.
SPA RxJS based router
var hashChangeEvent = Rx.Observable.fromEvent(window, 'hashchange');
var hash = location.hash;
var hashSubject = new Rx.BehaviorSubject(hash);
hashSubject.subscribe(function(hash) {
router(hash.replace('#', ''));
});
hashChangeEvent.subscribe(function(e) {
hashSubject.onNext(location.hash);
});
function router(hash) {
console.log('Do magic stuff to %s', hash)
}
@kristian76
Copy link
Author

On page load the hash is passed to router(), when ever the hash changes, the new hash is passed to the router. hashChangeEvent also knows the old hash

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment