The attached compiler()
function below applies JavaScript behavior to matching HTML elements as they enter the DOM.
This works like an Unpoly compiler Show archive.org snapshot for apps that don't use Unpoly Show archive.org snapshot , Custom Elements Show archive.org snapshot or any other mechanism that pairs JavaScript with HTML elements.
The compiler()
function is also a lightweight replacement for our legacy $.unobtrusive()
helper (no jQuery required).
Basic usage
Compilers are registered with a CSS selector and a callback function. The function is called with each new element that matches the selector.
The following compiler will remove flash messages (<div class="flash">
) after 5 seconds, or when clicked:
compiler('.flash', (element) => {
let removeFlash = () => element.remove()
element.addEventListener('click', removeFlash)
setTimeout(removeFlash, 5000)
})
Compilers are also a great tool to initialize JavaScript libraries. For example, the following will initialize
Tom Select
Show archive.org snapshot
on all <select>
elements:
compiler('select', (element) => {
new TomSelect(element, { searchEnabled: true })
})
Elements are compiled automatically
Matching elements will always be compiled automatically, regardless of when and how the element entered the DOM. There is no function to manually compile a new element.
The initial page is compiled once the DOM is parsed (DOMContentLoaded
event).
When matching elements enter the DOM after the initial page load, they are also compiled automatically. You do not need to manually activate elements that were added dynamically by JavaScript.
Cleaning up
To prevent memory leaks you sometimes need to run code when an element is removed from the DOM.
When your compiler returns a function, it is called when the element is detached from the DOM:
compiler('textarea.wysiwyg', (select) => {
let editor = new SuperEditor(select)
return () => editor.shutdown()
})