// app/redux/router.es6.js import m from 'mithril'; import {store, observeStore} from 'app/redux/store'; import {setRoute} from 'app/redux/action-creators'; window.addEventListener((m.route.mode === 'hash') ? 'hashchange' : 'popstate', () => passiveRouteChange(window.location)); observeStore(store, (state) => state.route, (route) => { if (!route.path) { return; } // Redirect with m.route() unless explicitly stated // Calls from passiveDispatch do not redirect. const redirect = (route.redirect === undefined || route.redirect); if (redirect) { m.route(route.path); } }); const passiveDispatch = (path, redirect = false) => ( store.dispatch(setRoute({ path, redirect })) ); const passiveRouteChange = (location) => { const path = m.route.mode === 'hash' ? location.hash.substring(1) : m.route.mode === 'search' ? location.search.substring(1) : location.pathname; if (path) { passiveDispatch(path); } }; /* m.route wrapper Call as: const routes = { '/home': router(m.component(home)) }; */ export default function(component) { return { controller: function() { const currentPath = store.getState().route.path; const newPath = m.route(); if (newPath !== currentPath) { passiveDispatch(newPath); } return new component.controller(); }, view: component.view }; };