'State Sync between components (Vanilla JS or Svelte)
I'm trying to create a basic example of an App in which there's 2 components: A and B. The goal is to make each component dispatch an event when both conditions are fulfilled:
- the component is mounted
- the library they all depend on is loaded
1st attempt: a new LibraryLoader Class
https://svelte.dev/repl/ef7876d4fa8847d1ad1e13eb616b95fa?version=3.46.2
So I thought that I would need a simple class which would be able to dispatch a simple event (not tied to a DOM node). So I decided to create a LibraryLoader class that inherits from a Dispatcher class (to be able to dispatch an event not tied to a DOM node). Below is my attempt
The problem here is that we get 2 instances of the LibraryLoader class (created by A & B) so it's not working. Maybe a static class which would inherit from the Dispatcher class ?(didn't find how to to it).
2nd Attempt: LibraryLoader as an object literal
https://svelte.dev/repl/5c9873bb0c59493dbe6dd6ed38bde276?version=3.46.2
Reading some posts about the singleton pattern led me to the idea of transforming the LibraryLoader class into a simple object literal. And it's working better here.
Components A and B are doing the same thing:
once the component is mounted, it executes checkstate() which will either ask for the Library to load, or just wait if another component has already asked for this.
once the library is mounted, it dispatches a "ready" event
Here it works pretty well. The library is not asked to be loaded twice and both A & B components are dispatching a "ready" event as expected. But there's one obvious drawback: the code is duplicated in A & B.
3rd attempt: Svelte Action
https://svelte.dev/repl/3a68a7efaa8f43be8bffda12dadb83a3?version=3.46.2
This attempt makes use of svelte action which seemed to be a potential solution as far as I understood how it works.
So, I put the code in loadAndGetReady.js but in the end, component B never gets READY so there's a catch here.
I'll take any advice :D
Thank you in advance
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
