What
// __ _// / _| make frontend great again | |// | |_ _ _ _ __ _ __ ___ _ __ ___ _ __ | |_// | _| | | | '_ \| '_ \ / _ \| '_ \ / _ \ '_ \| __|// | | | |_| | | | | |_) | (_) | | | | __/ | | | |_// |_| \__,_|_| |_| .__/ \___/|_| |_|\___|_| |_|\__|// | |// FUNPONENT |_| CONCEPT / TUTORIAL /* @jsx funponent */; // Progressively enhance these DOM elements// In realtime. Loading component mount points via AJAX? No problem.const selector = '[data-component=hello]'; // The component function. Must be pure, receives (data-* attributes) params// See https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/datasetconst component = <div> <p> Hello datasetcurrentName </p> <p> Change name: <input value=datasetcurrentName /> </p> <p> datasethash ? <code> locationhash = datasethash </code> : <a href='#put-some-hash-in-this-url'> Click to change #hash </a> </p> </div>; // Event map of selector maps, handled by component root elementconst events = 'input': // Event delegation, a CSS selector within root { elementdatasetcurrentName = eventtargetvalue; } ; // Init function. Can supply params via `dataset` (also async)// React equivalent: componentDidMountconst init = { elementdatasethash = locationhash;}; // Destroy function, called before deleting component// React equivalent: componentWillUnmountconst destroy = { // some cleanup code here, perhaps `clearInterval`}; // Bind all together (events, init and destroy are optional);
Initial state
<!-- maybe some initial server output. will be diffed against. -->
After funponent
Hello world Click to change #hash Hello another instance Click to change #hash
Notes
-
Whenever user types anything ('input' event),
data-current-name
is reflected -
Transition between states performed by morphdom
-
DOM is the single source of truth. More specifically: components'
data-*
attributes -
Nesting funponents is seamless, a component can render mount points for other components
-
MutationObserver is used to detect state changes
-
Browser developer tools can be used to inspect current state at any time