Created
November 24, 2016 21:43
-
-
Save akirattii/b5fc2cb9013e28c02c0ca058e35dd517 to your computer and use it in GitHub Desktop.
Loads all elements having `id` attr into the global as jQuery object dynamically
This file contains hidden or 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
| // Load elements having `id` attr on `document` as global variables (in directly under `window`) | |
| // They are loaded as jQuery object named as camelcase with prefix "$". | |
| // eg. An element is loaded as a variable named like this: id="ipt-name" -> `$iptName` | |
| exports.loadElements = function() { | |
| console.log(`[${moduleName}] auto-loading elements as jQuery elements...`); | |
| check(); | |
| let els = document.getElementsByTagName("*"); | |
| let el, camelId, varname; | |
| for (let len = els.length, i = 0; i < len; i++) { | |
| el = els[i]; | |
| if (el.id) { | |
| camelId = StringUtil.hypToCamel(el.id); | |
| varname = `$${camelId}`; | |
| console.log(`[${moduleName}] Loading element as '${varname}'`); | |
| window[`${varname}`] = $(`#${el.id}`); | |
| } | |
| } | |
| }; | |
| function check() { | |
| checkRequired(); | |
| } | |
| function checkRequired() { | |
| // Unless required modules exist, error thrown | |
| if (!window) throw Error(`[${moduleName}] 'window' object might not loaded yet`); | |
| if (!$) throw Error(`[${moduleName}] 'jQuery' is required`); | |
| if (!StringUtil) throw Error(`[${moduleName}] 'StringUtil' is required`); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment