Skip to content

Instantly share code, notes, and snippets.

@gx0r
Created February 28, 2016 15:18
Show Gist options
  • Save gx0r/46f574412a7f5bc0790f to your computer and use it in GitHub Desktop.
Save gx0r/46f574412a7f5bc0790f to your computer and use it in GitHub Desktop.
Routing with Mithril and Redux
var store = redux.createStore(function(state, action) {
var defaultState = {
view: LOGIN,
subview: '',
}
if (!state) {
return defaultState;
}
switch(action.type) {
// ...
}
})
store.subscribe(function () {
m.redraw();
var state = store.getState();
var viewState = {};
viewState.view = state.view;
viewState.subview = state.subview;
window.location.hash = JSON.stringify(viewState);
});
var lastLocation = {};
function handleNewHash() {
var location
try {
if (window.location.hash) {
var hash = window.location.hash.replace(/^#\/?|\/$/g, '');
location = JSON.parse(hash);
}
} catch (e) {
console.error(e);
}
if (location) {
if (!_.isEqual(lastLocation, location)) {
store.dispatch({
type: VIEW,
view: location.view,
subview: location.subview,
})
}
lastLocation = location;
}
}
// Handle the initial route and browser navigation events
handleNewHash()
window.addEventListener('hashchange', handleNewHash, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment