Skip to content

Instantly share code, notes, and snippets.

@estelsmith
Last active September 14, 2024 17:58
Show Gist options
  • Save estelsmith/bfc76a9f021645b9485930b8ee2081a3 to your computer and use it in GitHub Desktop.
Save estelsmith/bfc76a9f021645b9485930b8ee2081a3 to your computer and use it in GitHub Desktop.
Stupid simple DOM-router
(function (body) {
window.util = window.util || {};
window.util.DomRouter = Object.freeze({
ENTRY_COMMON: '_common',
FUNC_INIT: 'init',
FUNC_FINISH: 'finish',
execute: function (namespace, controllerName, actionName) {
const controller = namespace[controllerName];
if (controller === undefined) return;
const action = controller[actionName];
if (!(action instanceof Function)) return;
action();
},
load: function (namespace) {
const controller = body.getAttribute('data-controller');
const action = body.getAttribute('data-action');
this.execute(namespace, this.ENTRY_COMMON, this.FUNC_INIT);
if (controller) {
this.execute(namespace, controller, this.FUNC_INIT);
if (action) {
this.execute(namespace, controller, action);
}
this.execute(namespace, controller, this.FUNC_FINISH);
}
this.execute(namespace, this.ENTRY_COMMON, this.FUNC_FINISH);
}
});
})(document.body);
(function (document, DomRouter) {
DomRouter.load({
[DomRouter.ENTRY_COMMON]: {
[DomRouter.FUNC_INIT]: function () {
console.log('_common.init');
},
[DomRouter.FUNC_FINISH]: function () {
console.log('_common.finish');
}
},
project: {
[DomRouter.FUNC_INIT]: function () {
console.log('project.init');
},
summary: function () {
console.log('project.summary');
},
[DomRouter.FUNC_FINISH]: function () {
console.log('project.finish')
}
}
});
})(document, window.util.DomRouter);
<body data-controller="project" data-action="summary">
<!-- project.summary controller gets executed -->
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment