From 8f039f194455e6606e6d760c5cf9988f87d52863 Mon Sep 17 00:00:00 2001 From: Tor Morten Jensen Date: Wed, 20 Jun 2018 14:08:10 +0200 Subject: [PATCH 1/3] 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); From 2af688c4f1eb95684379dff5bacb7803cf3f8f86 Mon Sep 17 00:00:00 2001 From: Tor Morten Jensen Date: Wed, 20 Jun 2018 14:48:28 +0200 Subject: [PATCH 2/3] Rename to event --- resources/assets/scripts/util/Router.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/resources/assets/scripts/util/Router.js b/resources/assets/scripts/util/Router.js index 1afc214..f476722 100644 --- a/resources/assets/scripts/util/Router.js +++ b/resources/assets/scripts/util/Router.js @@ -29,7 +29,7 @@ class Router { bubbles: true, detail: { route, - fn + fn: event } })); From 2d9b9d16bf5991f136df7f4fb51295f5f4812e06 Mon Sep 17 00:00:00 2001 From: Tor Morten Jensen Date: Wed, 20 Jun 2018 14:50:43 +0200 Subject: [PATCH 3/3] Fix comma dangle lint error --- resources/assets/scripts/util/Router.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/resources/assets/scripts/util/Router.js b/resources/assets/scripts/util/Router.js index f476722..32b868c 100644 --- a/resources/assets/scripts/util/Router.js +++ b/resources/assets/scripts/util/Router.js @@ -29,8 +29,8 @@ class Router { bubbles: true, detail: { route, - fn: event - } + fn: event, + }, })); const fire = route !== '' && this.routes[route] && typeof this.routes[route][event] === 'function';