Skip to content

Instantly share code, notes, and snippets.

@D1360-64RC14
Created December 7, 2023 13:24
Show Gist options
  • Save D1360-64RC14/f2b69e6c53e93931ff111f94b779afb9 to your computer and use it in GitHub Desktop.
Save D1360-64RC14/f2b69e6c53e93931ff111f94b779afb9 to your computer and use it in GitHub Desktop.
HTMX Extension class boilerplate
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