Skip to content

Commit

Permalink
Execute registered JavaScript after htmx settles
Browse files Browse the repository at this point in the history
  • Loading branch information
bencroker committed Aug 20, 2024
1 parent ac6bd8a commit 00ba54d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Changed

- Components no longer render markup added via `{% html %}`, `{% css %}` and `{% js %}` tags during Sprig requests.
- The `sprig.registerJs(js)` function now executes the registered JavaScript after htmx settles.

## 3.3.2 - 2024-08-12

Expand Down
10 changes: 8 additions & 2 deletions src/services/RequestsService.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,15 @@ public function getRegisteredHtml(): string

// Append registered JS to the `beforeend:body` HTML block.
if (!empty($this->js)) {
$content = Html::script(implode('', $this->js));
// Execute the JS after htmx settles, at most once.
$js = implode(PHP_EOL, $this->js);
$content = <<<JS
document.addEventListener('htmx:afterSettle', function() {
$js
}, { once: true });
JS;
$this->html['beforeend:body'] = $this->html['beforeend:body'] ?? [];
$this->html['beforeend:body'][] = $content;
$this->html['beforeend:body'][] = Html::script($content);
}

foreach ($this->html as $swapSelector => $blocks) {
Expand Down

0 comments on commit 00ba54d

Please sign in to comment.