How do 2 Svelte components communicate without store / props / context?
✨❓ Svelte Question Time ❓✨
"You have a Svelte question, I have an answer" 😱😍
Sometimes, Svelte components need to communicate with each other, without using store, props, or context.
There are situations where the 2 components are not parent-child or siblings with each other. So, it does not make sense to communicate through props or context. The components may not be sharing the same data as well, so communicate through stores is out of the picture too.
An example of this, is in a e-commerce platform, where the 2 components are the shopping cart and an item card. The 2 components are not parent-child relationship, does not share the common parent (maybe except the root component). The 2 components do not share the same data, shopping cart uses cart data, and item card uses item data, (may have some commonalities, but they come from different API)
So, in this case, how would you notify the shopping cart, when you click "buy now" in an item card?
We are going to explore 2 approaches
1. Providing API to notify the component 04:53
2. Using Pub-Sub Pattern 13:03
🔗 REPL 1 https://svelte.dev/repl/507f3ca049494335899ef3d58296c830?version=3.38.2 🔗 REPL 2 https://svelte.dev/repl/4b7b07309ef3417c87a28c98933c13b9?version=3.38.2
🎧 Svelte Tutorial for Beginners https://www.youtube.com/playlist?list=PLoKaNN3BjQX3mxDEVG3oGJx2ByXnue_gR 🎧 Svelte Question Time https://www.youtube.com/playlist?list=PLoKaNN3BjQX1I9FmIoCaws4vUaoqezpc1
Related Resources Svelte https://svelte.dev Svelte REPL https://svelte.dev/repl
🥰 Support me https://www.buymeacoffee.com/lihautan
Want to learn more from me? Check out these links:
Twitter: https://twitter.com/lihautan Blog: https://lihautan.com/ Newsletter: https://lihautan.com/newsletter
Thanks for watching 🥰 -- with love, Li Hau