Posted about 1 month ago. Visible to the public.

Unobtrusive JavaScript helper to progressively enhance HTML

The attached compiler() function below applies JavaScript behavior to matching HTML elements as they enter the DOM.

This works like an Unpoly compiler Archive for apps that don't use Unpoly Archive , Custom Elements Archive 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() flash.addEventListener('click', removeFlash) setTimeout(removeFlash, 5000) })

Compilers are also a great tool to initialize JavaScript libraries. For example, the following will initialize Tom Select Archive 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() })

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Henning Koch
Last edit:
about 1 month ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more