Skip to content

Instantly share code, notes, and snippets.

@belozer
Last active September 7, 2016 00:30
Show Gist options
  • Save belozer/afcd138129d71f0f937266eca44ac944 to your computer and use it in GitHub Desktop.
Save belozer/afcd138129d71f0f937266eca44ac944 to your computer and use it in GitHub Desktop.
modules.define('router',
['store', 'store__router', 'router__routes', 'router-base', 'inherit', 'events', 'redux-watch'],
(provide, store, storeRouter, routes, RouterBase, inherit, events, watch) => {
const base = new RouterBase({routes: routes});
const _ = storeRouter.consts;
const Router = inherit(events.Emitter, /** @lends Router.prototype */{
__constructor: function() {
const w = watch(store.getState, 'router');
let preventHandler = this.currentHandler();
store.subscribe(w(r => {
const url = r.href;
let newHandler = this.currentHandler(url);
if (newHandler !== preventHandler) {
this.emit('change', {
url: url,
handler: newHandler,
preventHandler: preventHandler
});
preventHandler = newHandler;
}
}));
},
generate: (name, data) => {
return base.generate(name, data);
},
/**
* Текущий обработчик страницы (view)
* @param {string} href URL
* @return {string} имя обработчика
*/
currentHandler: href => {
if (typeof href === 'undefined') {
href = window.location.pathname;
}
const matched = base.match({path: href, method: 'GET'});
if (matched) {
return matched.definition.handler;
}
return new Error(`Handler for path '${href}' not founded`);
},
/**
* Получение текущих параметров из URL
* @return {object} params
*/
params: function() {
const url = store.getState().router.href;
let matched = base.match({path: url, method: 'GET'});
if (matched) {
return matched.parameters;
}
return false;
},
navigate: function(url) {
store.dispatch({type: _.NAVIGATE, href: url});
},
replace: function(url) {
store.dispatch({type: _.REPLACE, href: url});
}
});
/**
* @exports router
*/
provide(new Router());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment