hexops / vecty

Vecty lets you build responsive and dynamic web frontends in Go using WebAssembly, competing with modern web frameworks like React & VueJS.
BSD 3-Clause "New" or "Revised" License
2.79k stars 144 forks source link

question: initializing rendered HTML nodes via javascript #293

Closed soypat closed 2 years ago

soypat commented 2 years ago

Hey there! I need to initialize some Material Design components I rendered with vecty with a little bit of javascript, see here.

The initialization is simple enough, just call the constructor on the html node using getElementByID or similar. How would I go about this? I've been appending javascript unsafely to the end of my document but it is not exactly stable. See https://github.com/soypat/mdc/blob/main/examples/datatable/datatable_example.go#L68.

I think my unsafe approach would work better if I could somehow register a callback that is triggered once my component is rendered in the DOM. What would be the vecty way of doing this? Should we be looking for added API to see this work?

soypat commented 2 years ago

I think Material Design expects the user to also hold onto the javascript handle to the component so as to have feedback to user inputs i.e. Current level of the slider.

slimsag commented 2 years ago

I don't know anything about Material Design, but there are some others who have used it with Vecty in the past:

You should make certain that any DOM elements the material design library will attempt to modify on its own are isolated, i.e. using a vecty.Div with vecty.UnsafeHTML so that it is treated as an opaque element not owned by Vecty. See code example and further discussion around this in https://github.com/hexops/vecty/issues/236#issuecomment-496322050

The other things you may wish to look at are the Mounter, Unmounter, and RenderSkipper interfaces:

Hope that helps!

soypat commented 2 years ago

@slimsag Thank you so much! I'll look into it!

soypat commented 2 years ago

@slimsag sure enough Mount and RenderSkip worked like a charm. HAve not gotten around to using Unmount() yet, but if it works like I think it does and given Material.js has destroyer methods, should work just fine. Thank you again for your amazing explanations and for maintaining this great package :+1:

For posterity, here's the fix I applied: https://github.com/soypat/mdc/commit/ea678258e66f667a51199883b5fe0a97274d5717. Look for the Mount() and RenderSkip() implementations on Slider and Tooltip types.