Last active
November 20, 2025 06:29
-
-
Save rndme/5b73095626022fa36f29c86cacbc32c8 to your computer and use it in GitHub Desktop.
put functions as event handlers in tagged template strings
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
| // a function wrap that lets you put functions as event handlers in template strings, allowing closure w/ event code | |
| // returns an html event=uid into the string template, then soon later swaps for the actual passed function | |
| function on(string) { // tag template function to bind local variables in templated html | |
| let values = [...arguments].slice(1); | |
| values = values.map(function(expression) { | |
| if(typeof expression != "function") return expression; | |
| let id = "on_" + Math.random().toString(36).slice(-6), | |
| evtName = expression.toString().split("=")[0].trim(); | |
| setTimeout(function _() { // event upgrader. runs after creation/return. | |
| let elm = document.querySelector(`[${evtName}='${id}']`); | |
| if(!elm) return setTimeout(_, 250); | |
| elm.removeAttribute(evtName); | |
| elm[evtName] = expression; | |
| }, 133); | |
| return evtName + "=" + id; | |
| }); | |
| return string.map(function(s, i) { | |
| return s + (values[i] || ""); | |
| }).join(""); | |
| } /* end on() tag template function */ | |
| //////////////////////////////////////////////////////////////////// | |
| // simple POC demo of private member access from public HTML events: | |
| (function() { // non-global scope | |
| function someLocal() { | |
| alert(123); | |
| } /* end someLocal() */ | |
| document.body.innerHTML = on` <h3>embedded private functions as inline events</h3> | |
| <button onclick="someLocal()">old-N-busted</button> | |
| <button ${onclick=>someLocal()}>New Hotness</button> `; | |
| }()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment