Created
December 7, 2023 13:24
-
-
Save D1360-64RC14/f2b69e6c53e93931ff111f94b779afb9 to your computer and use it in GitHub Desktop.
HTMX Extension class boilerplate
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
import htmx from "htmx.org"; | |
class ExtensionName { | |
/** @private @type {WeakMap<HTMLElement, ExtensionName>} */ | |
static _elementInstances = new WeakMap(); | |
/** @private @type {HTMLElement} */ _rootElement; | |
/** | |
* @param {HTMLElement} element | |
*/ | |
constructor(element) { | |
this._rootElement = element; | |
} | |
/** | |
* @param {string} name | |
* @param {CustomEvent} evt | |
*/ | |
static onEvent(name, evt) { | |
if (!(evt.detail.elt instanceof HTMLElement)) return; | |
let instance = ExtensionName._elementInstances.get(evt.detail.elt); | |
if (!instance) { | |
instance = new ExtensionName(evt.detail.elt); | |
ExtensionName._elementInstances.set(evt.detail.elt, instance); | |
} | |
switch (name) { | |
case "htmx:afterProcessNode": | |
instance._afterProcessNode(evt); | |
break; | |
} | |
} | |
/** | |
* @private | |
* @param {CustomEvent} evt | |
*/ | |
_afterProcessNode(evt) {} | |
} | |
htmx.defineExtension("extension-name", { | |
onEvent: ExtensionName.onEvent, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment