Skip to content

Instantly share code, notes, and snippets.

@wtpayne
Created January 2, 2021 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wtpayne/b904785398b8411f0d582d135d1fecf6 to your computer and use it in GitHub Desktop.
Save wtpayne/b904785398b8411f0d582d135d1fecf6 to your computer and use it in GitHub Desktop.
HTMX extension for xact
htmx.defineExtension('xact', {
onEvent : function(name_evt_src, evt_src) {
// New logic is either swapped in or sent via SSE.
is_swap = (name_evt_src === 'htmx:afterSwap');
is_sse = name_evt_src.startsWith('htmx:sse:');
is_update = (is_swap || is_sse);
if (!is_update) {
return;
}
// Event handling logic is stored in the window.xact global.
if (!('xact' in window)) {
window.xact = {};
}
// Ignore events where handling logic already exists.
if (name_evt_src in window.xact) {
return;
}
// Update the callbacks where we have new ones provided.
elt_target = evt_src.target;
list_found = htmx.findAll(elt_target, '[xact], [data-xact]');
for (var idx = 0; idx < list_found.length; idx++) {
elt_found = list_found[idx];
name_evt_tgt = 'htmx:sse:' + elt_found.id;
if (!(name_evt_tgt in window.xact)) {
window.xact[name_evt_tgt] = {};
}
node_new = eval(elt_found.dataset.xact);
node_old = window.xact[name_evt_tgt];
if ('step' in node_old) {
elt_target.removeEventListener(name_evt_tgt,
node_old.step);
}
if ('step' in node_new) {
elt_target.addEventListener(name_evt_tgt,
node_new.step);
}
window.xact[name_evt_tgt] = node_new;
window.xact[name_evt_tgt].reset(name_evt_tgt);
}
}})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment