Last active
September 14, 2024 17:58
-
-
Save estelsmith/bfc76a9f021645b9485930b8ee2081a3 to your computer and use it in GitHub Desktop.
Stupid simple DOM-router
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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