Note! This library is just an experiment and not intended for production use (yet).
yarn add embroidery
or
npm i embroidery
Add controller, target and action attributes to your HTML
<!-- HTML somewhere in your web app -->
<div data-controller="myController">
<input data-target="name" type="text" />
<button data-action="click->greet">Greet</button>
<span data-target="output"></span>
</div>
Create a controller in javascript.
// my-controller.js
const myController = {
greet({ name, output }) {
output.textContent = name.value
},
}
Register your controller in your main javascript file.
import { Embroidery } from 'embroidery'
import { myController } from 'my-controller'
let app = Embroidery.start()
app.register({ myController })
Add a partial (async external html). This is good for inserting remote fragments into your HTML to keep page loads fast.
<div data-partial="/endpoint-that-returns-html"></div>
Some elements have default actions, which means you don't have to specify click, submit etc. For example:
// Before
<button data-action="click->hello">Hello</button>
// After
<button data-action="hello">Hello</button>
Element | Event |
---|---|
a | 'click' |
button | 'click' |
form | 'submit' |
input | 'input' |
select | 'change' |
textarea | 'input' |
If you want to have multiple actions you can separate them with a blank space.
<div data-controller="manyActions">
<div data-action="mouseover->doThis mouseout->doThat">Do this or that</div>
</div>
If you have multiple targets you need to add []
to access them as an array in your controller. The array will be appended with <name>Targets
.
<div>
<div data-target="hello[]">Hello to you</div>
<div data-target="hello[]">Hello to me</div>
<div data-target="hello[]">Hello to everyone</div>
</div>
// hello-controller.js
const helloController = {
init({ helloTargets }) {
helloTargets.forEach((target) => {
//...
})
},
}