Skip to content

JavaScript hooks and debugging

Greg Bowler edited this page Apr 10, 2026 · 1 revision

Flux is deliberately small, but it still needs to cooperate with any JavaScript we add ourselves.

Event listeners are reattached after swaps

Internally, Flux wraps addEventListener so it can keep a record of listeners attached to elements. When a Flux update replaces an element, Flux reattaches those listeners to the matching new element.

That means code like this continues to work after a refresh:

const button = document.querySelector("button.tracker");
button.addEventListener("click", () => {
	console.log("tracked");
});

As long as the new document contains the corresponding replacement element, Flux carries the listener over.

New Flux elements are initialised automatically

If an update inserts new elements containing data-flux, Flux scans and initialises them as part of the replacement process. This is particularly important for:

  • nested submit buttons
  • new Flux links
  • live regions introduced by an update

Enable debug logging

When we are working on Flux itself, or trying to understand a tricky page, we can enable debug mode:

import { FluxDebug } from "@phpgt/flux";
import "@phpgt/flux";

With debug mode enabled, Flux logs extra detail about event registration, target storage, and focus restoration.

Failure behaviour

If Flux cannot process a returned document properly, it logs an error and reloads the page. The most common reason would be a response that is not a complete HTML document.

Important

Flux is designed around full HTML responses. If we return a fragment with no <head>, Flux treats that as an error and falls back to a normal reload.

Testing the behaviour

This repository includes two useful test layers:

  • vitest unit tests for the JavaScript classes in src/
  • behat browser tests for the runnable examples in example/

The browser suite is the best source of truth for end-to-end behaviour because it exercises the real DOM update flow.


The walkthrough is complete. See the list of flux attributes as the reference sheet, or browse the runnable examples.

Clone this wiki locally