From 6a6070d91f21023de1df839cf96b8a73361e01f4 Mon Sep 17 00:00:00 2001 From: strangeRabbit777 Date: Wed, 10 Jun 2020 16:09:00 -0700 Subject: [PATCH] Trigger events on new content, rather than triggering element, since triggering element may have been replaced fixes https://github.com/bigskysoftware/htmx/issues/79 --- src/htmx.js | 6 +++--- test/core/events.js | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/src/htmx.js b/src/htmx.js index 85a1ed1e..a7ea72db 100644 --- a/src/htmx.js +++ b/src/htmx.js @@ -1406,7 +1406,7 @@ return (function () { } // don't process 'No Content' response if (this.status !== 204) { - if (!triggerEvent(elt, 'beforeSwap.htmx', eventDetail)) return; + if (!triggerEvent(target, 'beforeSwap.htmx', eventDetail)) return; var resp = this.response; withExtensions(elt, function(extension){ @@ -1430,8 +1430,8 @@ return (function () { if (elt.classList) { elt.classList.add("htmx-settling"); } + triggerEvent(elt, 'afterSwap.htmx', eventDetail); }); - triggerEvent(elt, 'afterSwap.htmx', eventDetail); if (anchor) { location.hash = anchor; } @@ -1443,12 +1443,12 @@ return (function () { if (elt.classList) { elt.classList.remove("htmx-settling"); } + triggerEvent(elt, 'afterSettle.htmx', eventDetail); }); // push URL and save new page if (shouldSaveHistory) { pushUrlIntoHistory(pushedUrl || path); } - triggerEvent(elt, 'afterSettle.htmx', eventDetail); } if (swapSpec.settleDelay > 0) { diff --git a/test/core/events.js b/test/core/events.js index c4d893f3..dfe5705b 100644 --- a/test/core/events.js +++ b/test/core/events.js @@ -82,5 +82,41 @@ describe("Core htmx Events", function() { } }); + it("afterSwap.htmx is called when replacing outerHTML", function () { + var called = false; + var handler = htmx.on("afterSwap.htmx", function (evt) { + called = true; + }); + try { + this.server.respondWith("POST", "/test", function (xhr) { + xhr.respond(200, {}, ""); + }); + var div = make(""); + div.click(); + this.server.respond(); + should.equal(called, true); + } finally { + htmx.off("afterSwap.htmx", handler); + } + }); + + it("afterSettle.htmx is called when replacing outerHTML", function () { + var called = false; + var handler = htmx.on("afterSettle.htmx", function (evt) { + called = true; + }); + try { + this.server.respondWith("POST", "/test", function (xhr) { + xhr.respond(200, {}, ""); + }); + var div = make(""); + div.click(); + this.server.respond(); + should.equal(called, true); + } finally { + htmx.off("afterSettle.htmx", handler); + } + }); + });