I'm trying to use native web components for one of my UI project and for this project, I'm not using any frameworks or libraries like Polymer etc. I would like to know is there any best way or other way to communicate between two web components like we do in angularjs/angular (like the message bus concept).
Currently in UI web-components, I'm using dispatchevent for publishing data and for receiving data, I'm using addeventlistener. For example, there are 2 web-components, ChatForm and ChatHistory.
// chatform webcomponent on submit text, publish chattext data
this.dispatchEvent(new CustomEvent('chatText', {detail: chattext}));
// chathistory webcomponent, receive chattext data and append it to chat list
this.chatFormEle.addEventListener('chatText', (v) => {console.log(v.detail);});
Please let me know what other ways work for this purpose. Any good library like postaljs etc. that can easily integrate with native UI web components.
+1 for both other answers, Events are the best because then Components are loosly coupled
Note that in the
detail
of a Custom Event you can send anything you want.Event driven function execution:
So I use (psuedo code):
Elements that define a Solitaire/Freecell game:
When a card (dragged by the user) needs to be moved to another pile,
it sends an Event (bubbling up the DOM to the game element)
Note:
reply
is a function definitionBecause all piles where told to listen for
___FINDSLOT___
Events at the game element ...Only the one pile matching the
evt.detail.id
responds:!!! by executing the function
card
sent inevt.detail.reply
And getting technical: The function executes in
pile
scope!(the above code is pseudo code!)
Why?!
Might seem complex;
The important part is that the
pile
element is NOT coupled to the.move()
method in thecard
element.The only coupling is the name of the Event:
___FINDSLOT___
!!!That means
card
is always in control, and the same Event(Name) can be used for:pile
makes a Full-House?In my E-lements code
pile
isn't coupled toevt.detail.id
either,CustomEvents only send functions
.say()
and.on()
are my custom methods (on every element) fordispatchEvent
andaddEventListener
I now have a handfull of E-lements that can be used to create any card game
.. will be on GitHub later this month
sneak peek:
No need for any libraries, write your own 'Message Bus'
My
element.on()
method is only a few lines of code wrapped around theaddEventListener
function, so they can easily be removed:.say( )
is a oneliner:Custom Events is the best solution if you want to deal with loosely coupled custom elements.
On the contrary if one custom element know the other by its reference, it can invoke its custom property or method:
In the last example above communication is done through a dedecated object exposed via the
api
property.You could also use a mix of Events (in one way) and Methods (in the other way) depending on how custom elements are linked.
Lastly in some situations where messages are basic, you could communicate (string) data via HTML attributes:
If you look at Web Components as being like built in components like
<div>
and<audio>
then you can answer your own question. The components do not talk to each other.Once you start allowing components to talk directly to each other then you don't really have components you have a system that is tied together and you can not use Component A without Component B. This is tied too tightly together.
Instead, inside the parent code that owns the two components, you add code that allows you to receive events from component A and call functions or set parameters in Component B, and the other way around.
Having said that there are two exceptions to this rule with built in components:
The
<label>
tag: It uses thefor
attribute to take in an ID of another component and, if set and valid, then it passes focus on to the other component when you click on the<label>
The
<form>
tag: This looks for form elements that are children to gather the data needed to post the form.But both of these are still not TIED to anything. The
<label>
is told the recipient of thefocus
event and only passes it along if the ID is set and valid or to the first form element as a child. And the<form>
element does not care what child elements exist or how many it just goes through all of its descendants finding elements that are form elements and grabs theirvalue
property.But as a general rule you should avoid having one sibling component talk directly to another sibling. The methods of cross communications in the two examples above are probably the only exceptions.
Instead your parent code should listen for events and call functions or set properties.
Yes, you can wrap that functionality in an new, parent, component, but please save yourself a ton of grief and avoid spaghetti code.
As a general rule I never allow siblings elements to talk to each other and the only way they can talk to their parents is through events. Parents can talk directly to their children through attributes, properties and functions. But it should be avoided in all other conditions.