Skip to content

Events API that auto-removes handlers on destroy - #33

Open
domchristie wants to merge 1 commit into
makenosound:mainfrom
domchristie:events
Open

Events API that auto-removes handlers on destroy#33
domchristie wants to merge 1 commit into
makenosound:mainfrom
domchristie:events

Conversation

@domchristie

Copy link
Copy Markdown

I have started migrating Stimulus controllers to Defo view functions in my podcast player app, and thought it might be useful to handle events with a nice API.

This pull request aims to do just that! After the el and props arguments, this adds a third: an object containing function for registering events (on), and an abort signal (signal).

on

Event handlers registered with on are automatically removed when the view is destroyed.

on can register events that target the view el:

function viewName(el, props, { on }) {
  on("click", (event) => { ... });
}

or a descendant of el matching a selector:

function viewName(el, props, { on }) {
  on("click", "[data-action='remove']", (event, matchedEl) => {
    matchedEl.closest("li").remove();
  });
}

or an explicit target, useful for events on the window/document, or for events that don’t bubble, like focus or blur:

function viewName(el, props, { on }) {
  on(window, "scroll", (event) => { ... });
}

function anotherViewName(el, props, { on }) {
  on(el.querySelector("input"), "blur", (event) => { ... });
}

More than one listener can be bound to the same event:

function viewName(el, props, { on }) {
  on("click", doSomething);
  on("click", doSomethingElse);
}

signal

An abort signal is used to remove event listeners but it's also made available for use in view functions. For example, it could be passed into a fetch to abort it when the view is destroyed:

function viewName(el, props, { signal }) {
  fetch(props.url, { signal }).then((response) => { ... });
}

Disclosure

This code was largely produced by Claude Code. I have reviewed every line and it seems reasonable and good quality. The pull request was written up by me. However, if this isn't your thing (for this reason, or any other ones!), that's cool!

Lastly, thanks for defo! It's a joy :)

@domchristie

Copy link
Copy Markdown
Author

Alternatively, rather than a third argument, it might be nice for view functions to just accept an object e.g.:

function myView({ el, props, on, signal }) { … }

I reckon this could be made backwards-compatible by checking the arguments type/count

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant