bigskysoftware / _hyperscript

a small scripting language for the web
BSD 2-Clause "Simplified" License
3.07k stars 147 forks source link

Allow construct to listen to "reactive" events #457

Open jquesada2016 opened 1 year ago

jquesada2016 commented 1 year ago

I've recently come to the conclusion that it'd be a really nice addition to the language to declare an event with the from clause to be dynamic to DOM changes.

For example:

<body _="on click from <button /> call alert('a button was clicked')">
  <!-- ...content -->
</body>

Now, the above will only react to button clicks for the buttons that existed at the time the <body /> loads. It would be nice to be able to dynamically add event listeners as elements are added and removed from the DOM, as long as they match the selector. Perhaps something like:

<body _="on click from all <button /> call alert('a button was clicked')">
  <!-- ...content -->
</body>

Here I introduced the all modifier, which would opt-in to this behavior.

Any thoughts on this?

dz4k commented 1 year ago

Use event delegation for this. https://denizaksimsek.com/2021/hyperscript-event-delegation/

on click from body
  tell closest <button /> to target
    alert("a button was clicked")