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]();
}
});
```
This commit is contained in:
committed by
GitHub
parent
fd2a94fa1b
commit
8f039f1944
@@ -25,6 +25,14 @@ class Router {
|
|||||||
* @param {string} [arg] Any custom argument to be passed to the event.
|
* @param {string} [arg] Any custom argument to be passed to the event.
|
||||||
*/
|
*/
|
||||||
fire(route, event = 'init', arg) {
|
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';
|
const fire = route !== '' && this.routes[route] && typeof this.routes[route][event] === 'function';
|
||||||
if (fire) {
|
if (fire) {
|
||||||
this.routes[route][event](arg);
|
this.routes[route][event](arg);
|
||||||
|
|||||||
Reference in New Issue
Block a user