From 34dda10f9ef3cfbe97d0816d0d798d3c48c6dcef Mon Sep 17 00:00:00 2001 From: basvk Date: Wed, 11 Dec 2024 22:27:34 +0100 Subject: [PATCH] Do not execute hx-trigger="load" on re-initialization of an existing node (#2976) * Do not execute hx-trigger="load" on re-initialization of an existing node * simplify initNode firstInit logic --- src/htmx.js | 11 +++++++---- test/core/api.js | 11 +++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/htmx.js b/src/htmx.js index 6e5e4065d..29c8d1852 100644 --- a/src/htmx.js +++ b/src/htmx.js @@ -693,6 +693,7 @@ var htmx = (function() { * @property {XMLHttpRequest} [xhr] * @property {(() => void)[]} [queuedRequests] * @property {boolean} [abortable] + * @property {boolean} [firstInitCompleted] * * Event data * @property {HtmxTriggerSpecification} [triggerSpec] @@ -1625,7 +1626,7 @@ var htmx = (function() { }) } deInitOnHandlers(element) - forEach(Object.keys(internalData), function(key) { delete internalData[key] }) + forEach(Object.keys(internalData), function(key) { if (key !== 'firstInitCompleted') delete internalData[key] }) } /** @@ -2632,7 +2633,7 @@ var htmx = (function() { }, observerOptions) observer.observe(asElement(elt)) addEventListener(asElement(elt), handler, nodeData, triggerSpec) - } else if (triggerSpec.trigger === 'load') { + } else if (!nodeData.firstInitCompleted && triggerSpec.trigger === 'load') { if (!maybeFilterEvent(triggerSpec, elt, makeEvent('load', { elt }))) { loadImmediately(asElement(elt), handler, nodeData, triggerSpec.delay) } @@ -2839,11 +2840,12 @@ var htmx = (function() { return } const nodeData = getInternalData(elt) - if (nodeData.initHash !== attributeHash(elt)) { + const attrHash = attributeHash(elt) + if (nodeData.initHash !== attrHash) { // clean up any previously processed info deInitNode(elt) - nodeData.initHash = attributeHash(elt) + nodeData.initHash = attrHash triggerEvent(elt, 'htmx:beforeProcessNode') @@ -2868,6 +2870,7 @@ var htmx = (function() { initButtonTracking(elt) } + nodeData.firstInitCompleted = true triggerEvent(elt, 'htmx:afterProcessNode') } } diff --git a/test/core/api.js b/test/core/api.js index 290363911..d22919eb5 100644 --- a/test/core/api.js +++ b/test/core/api.js @@ -393,6 +393,17 @@ describe('Core htmx API test', function() { div.innerHTML.should.equal('delete') }) + it('does not trigger load on re-init of an existing element', function() { + this.server.respondWith('GET', '/test', 'test') + var div = make('
') + this.server.respond() + div.innerHTML.should.equal('test') + div.setAttribute('hx-swap', 'afterbegin') + htmx.process(div) + this.server.respond() + div.innerHTML.should.equal('test') + }) + it('onLoad is called... onLoad', function() { // also tests on/off this.server.respondWith('GET', '/test', "
")