Headless components
With the introduction of findSlot in Modjool v1.1,
creating headless components becomes a simple task.
What is a headless component?
A headless component is essentially a component that provides functionality, without specifying
an interface, and separates the logic and behaviour from the visuals. An API is then provided
to apply the headless components to a user-defined UI.
Creating headless components
Within Modjool, headless elements can be implemented by making use of findSlot,
(more info),
to apply the functionality to slotted elements:
modjool.create({
tag: 'toggle-box',
complete: ({ findSlot }) => {
findSlot`switch`.onclick = () => findSlot`menu`.toggleAttribute('hidden')
},
html: ({ slot }) => `
${slot.switch}
${slot.box}
`
})
Here, the box slot is given the hidden
attribute, and we then toggle it with a click event on the switch slot:
<toggle-box>
<button slot="switch">Toggle box</button>
<div slot="box" hidden>
This is a hidden box
</div>
</toggle-box>
This is a hidden box
Another example
In this example, a click event to copy the innerHTML is assigned
to each child of the items slot element:
modjool.create({
tag: 'item-select',
js: ({ findSlot }) => {
const current = findSlot`current`
for (const child of findSlot`items`.children) {
child.onclick = () => current.innerHTML = 'Current: ' + child.innerHTML
}
},
html: ({ slot }) => `
${slot.current}
${slot.items}
`
})
<item-select>
<span slot="current">Click on an item!</span>
<ul slot="items">
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
</ul>
</item-select>
Click on an item!