3 ms·
Something I've never understood how to handle with vanilla web components: if there's some state that needs to be shared and kept in sync between multiple compo
by lgessler 5y ago
Something I've never understood how to handle with vanilla web components: if there's some state that needs to be shared and kept in sync between multiple components, how do you do it?
(For comparison, in React you can pass the state down as props from a common ancestor, and in Clojure frameworks all app state is in a giant object referenced by components as needed.)
- ithkuil 5y agoThe nice thing about web components, is that this problem is orthogonal go the componentization of the components. How do you pass the state between an input button and a label? Whatever technique you choose to do that (including react!) you can use it with web components. Some frameworks like react though also solve the componentization problem, so since web components are not necessary there (and weren't ready yet when react first came out), they tend to not get used to react and friends, even if they would technically work.
- 1337shadow 5y agoYou just addEventListenner on change or input and update your state. Nothing special here.
- jjcm 5y agoFor passing upwards I typically fire a custom event, with data in the detail field. For passing downwards, I have the parent delegate attribute changes on the children as much as possible. This limits you to only passing string values downwards, but it keeps the html mirrored to the state, which has a simplicity to it that I prefer. An example of this would be a radio-group and radio-element. When an element is clicked it fires a "clicked" event to the parent radio-group. The radio-group then toggles on "selected" for the clicked element, and removes the previously selected element's "selected" attribute.
- hardwaresofton 5y agoSo basically, the answer is to do it how you did before (shared global state or events etc) I recently took the time to explore a new idea I haven’t seen explored before —- services as DOM elements: https://www.vadosware.io/post/sade-pattern-services-as-dom-elements/ https://www.vadosware.io/post/sade-pattern-services-as-dom-e... Straight to the repo: https://gitlab.com/mrman/services-as-dom-elements https://gitlab.com/mrman/services-as-dom-elements The idea is simple, use references to get at other DOM elements that happen to act like whatever kind of store you need