DEV Community

Deniz Akşimşek
Deniz Akşimşek

Posted on • Originally published at denizaksimsek.com on

Event Delegation in _hyperscript

on click
  tell the closest <li/> to the target
    remove yourself
    -- do more stuff...
    -- "you" refers to the clicked list item
Enter fullscreen mode Exit fullscreen mode

I’ve seen some people use a pattern like this:

<ul>
  {% for item in items %}
    <li _="on click remove me"></li>
  {% endfor %}
</ul>
Enter fullscreen mode Exit fullscreen mode

This is convenient to write if you have a server-side templating system, but has a few issues:

  • The code needs to be parsed N times where N is the number of items.
  • The resulting HTML is bloated.
  • If you add more items client-side, you need to repeat the code there.

The pattern for resolving this is called event delegation. Here’s how you might do it in JavaScript:

ul.addEventListener('click', e => {
  const li = e.target.closest('li')
  if (!li) return
  li.remove()
})
Enter fullscreen mode Exit fullscreen mode

We add a single event listener to the enclosing list, which finds the item that was clicked and manipulates it.

In _hyperscript, the tell command allows us to manipulate an element other than me conveniently, by changing the implicit target from me to ypu, which refers to the element being “told”.

Top comments (0)