From 8f039f194455e6606e6d760c5cf9988f87d52863 Mon Sep 17 00:00:00 2001 From: Tor Morten Jensen Date: Wed, 20 Jun 2018 14:08:10 +0200 Subject: [PATCH] Dispatch event when firing routes It is especially neat when importing the scripts from the parent theme in a child theme. In one of my themes I do it like this: ```js // routes.js import home from './routes/home' export default { home: { init() { console.log('Home route fired.') } } } ``` ```js // main.js /** * Parent Themes Script */ import '../../../../core-theme/resources/assets/scripts/main'; /** * Internal modules */ import routes from './routes' /** * Hook in to the parent themes router */ document.addEventListener('routed', e => { let route = e.detail.route, fn = e.detail.fn; if (routes[route] && typeof routes[route][fn] === 'function') { routes[route][fn](); } }); ``` --- resources/assets/scripts/util/Router.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/resources/assets/scripts/util/Router.js b/resources/assets/scripts/util/Router.js index 372594e..1afc214 100644 --- a/resources/assets/scripts/util/Router.js +++ b/resources/assets/scripts/util/Router.js @@ -25,6 +25,14 @@ class Router { * @param {string} [arg] Any custom argument to be passed to the event. */ fire(route, event = 'init', arg) { + document.dispatchEvent(new CustomEvent('routed', { + bubbles: true, + detail: { + route, + fn + } + })); + const fire = route !== '' && this.routes[route] && typeof this.routes[route][event] === 'function'; if (fire) { this.routes[route][event](arg);