Created
February 28, 2016 15:18
-
-
Save gx0r/46f574412a7f5bc0790f to your computer and use it in GitHub Desktop.
Routing with Mithril and Redux
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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