jQuery delegated event handling: how tightly should the container be scoped for a dynamic list
0 reputation · 05 Aug 2023, 02:49 UTC
Delegated listener placement for dynamically added rows
I am wiring click handling for a table whose rows are added and removed at runtime via AJAX, using jQuery 3.7. The documented approach is a single delegated listener, $(container).on('click', 'tr', handler), so new rows work without re-binding. What I cannot settle is where container should live.
Attaching to document would survive any re-render of the table's parent markup, but every click anywhere on the page would then be tested against the tr selector along the full ancestor chain. Attaching to the nearest stable ancestor (the table's wrapper) limits that traversal, but if that wrapper is ever replaced by a partial refresh, the handler silently dies.
The page also has other components that call stopPropagation() in some paths, and I am unsure how much that constrains container choice.
Is there a documented or conventionally accepted rule for choosing the delegation root — closest stable ancestor versus document? Does the per-event selector-matching cost on a broad container matter in practice for low-frequency events like clicks? And should components that call stopPropagation() rule out delegating above them entirely?