Created
April 2, 2023 12:32
-
-
Save rajeshpillai/cfce74c066041cfdbe9a10b0877a016a to your computer and use it in GitHub Desktop.
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
| console.clear(); | |
| function html(strings, ...values) { | |
| // Combine the strings and values into a single string | |
| const combined = strings.reduce((acc, str, i) => acc + str + (values[i] !== undefined ? `§${i}§` : ''), ''); | |
| console.log({combined}); | |
| // Create a temporary container to hold the HTML string | |
| const container = document.createElement('div'); | |
| container.innerHTML = combined; | |
| // Attach event listeners | |
| container.querySelectorAll('*').forEach(element => { | |
| const attributes = [...element.attributes]; | |
| attributes.forEach(attr => { | |
| if (attr.name.startsWith('@')) { | |
| let eventName = attr.name.slice(1); | |
| const index = parseInt(attr.value.slice(1, -1), 10); | |
| const handler = values[index]; | |
| element.removeAttribute(attr.name); | |
| // Check if the provided handler is a function | |
| if (typeof handler === 'function') { | |
| eventName = eventName.substr(2); | |
| console.log("function::", element, eventName, handler); | |
| // This work (event should not have 'on' prefix) | |
| element.addEventListener(eventName, handler); | |
| // This works (event Should have 'on' prefix) | |
| //element[eventName] = handler; | |
| } else { | |
| console.error(`EventHandlerError: The provided event handler is not a function.`); | |
| } | |
| } | |
| }); | |
| }); | |
| // Return the first child element | |
| return container.firstElementChild; | |
| } | |
| // Example | |
| // Example usage: create a button with a click event handler | |
| const root = document.getElementById('root'); | |
| const onclick = () => { | |
| alert('Button clicked!'); | |
| }; | |
| const onMouseMove = (e) => { | |
| console.log("mousemove: (e) ", e.offsetX, e.offsetY); | |
| } | |
| const buttonHtml = html` | |
| <div> | |
| <h1>Testing DOM and events </h1> | |
| <button | |
| @onclick=${onclick} | |
| @onmousemove=${onMouseMove}>Click me | |
| </button> | |
| </div> | |
| `; | |
| console.log(buttonHtml); | |
| document.body.appendChild(buttonHtml); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment