vanjs-org / van

🍦 VanJS: World's smallest reactive UI framework. Incredibly Powerful, Insanely Small - Everyone can build a useful UI app in an hour.
https://vanjs.org
MIT License
3.77k stars 87 forks source link

Add a callback with just created element #242

Closed RuthgerD closed 7 months ago

RuthgerD commented 7 months ago

To keep it short, I am looking for a way to do this: https://svelte.dev/docs/element-directives#bind-this

where today you need to create the element, assign it to a variable and then return the variable again.

What I would like to write is something along the lines of:

const el = state(null)

return div(() => a({self: el}, /* some text */), ...)

but today I need to write:

const el = state(null)

return div(() => {
    const it = a({self: el}, /* some text */)
    el.val = it
    return el.val
}, ...)

similarly, I find myself sometimes needing to access an element from a callback, and the dance to do this less nice as well.

I hope this can be somehow considered, thanks!

Tao-VanJS commented 7 months ago

For your specific example, I think you can simply have:

return div(() => el.val = a({self: el}, /* some text */),
  ...
)

That said, it's advised to avoid setting the value of the state to a DOM element, see https://vanjs.org/advanced#why-not-dom-valued-states.

RuthgerD commented 7 months ago

My hopefully legitimate use case is scrolling the container from within a callback that is defined within the body of the container I want to scroll, but your suggestion actually fits nicely I think; I am not too literate in all the javascript tricks! thanks :)