Communication between components (universal)

Written by shystruk | Published 2018/05/14
Tech Story Tags: javascript | programming | technology | web-components | web-development

TLDRvia the TL;DR App

Photo by Colwyn on Flickr

Communication is important, especially neighborhood communication 😎 Let’s collect communication approaches between components.

I remember a time when I jumped to Angular and while developing I had to find the best way to communicate between components. In Angular we may dispatch events ($emit, $broadcast), in React use Redux etc. Each framework has own approaches, but we may have general solutions no matter of framework, web components. So, let’s collect them.

We are going to talk about neighborhood communication 😎

Custom Events

Custom Event is a good approach to dispatch events and listen. You should listen event from target [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element "Element is the most general base class from which all objects in a Document inherit. It only has methods and properties common to all kinds of elements. More specific classes inherit from Element."), [Document](https://developer.mozilla.org/en-US/docs/Web/API/Document "The Document interface represents any web page loaded in the browser and serves as an entry point into the web page's content, which is the DOM tree."), and [Window](https://developer.mozilla.org/en-US/docs/Web/API/Window "The window object represents a window containing a DOM document; the document property points to the DOM document loaded in that window."), but the target may be any object that supports events (such as [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest)). It does not work in IE but for that we have a Polyfill solution.

So, Custom Event Service is going to look like that:

Communication phase:

Publish/Subscribe

The Publish/Subscribe pattern encourage us to think hard about the relationships between different parts of our application.

Publish/Subscribe pattern saves a TOPIC name and reference to a callback. When you publish the TOPIC it calls the callback.

👯 Difference between Custom Event and Pub/Sub

Callbacks are not subscribed to particular events. Every payload is dispatched to every registered callback.

Watching DOM tree

Another way to communicate is watching DOM changes. You may observe node element changes (attributes, childList, characterData) and when DOM changes occur observer will invoke a specified callback function.

👏 Thank you for reading. Suggestions, comments, thoughts are welcome 👍

If you like this, clap, follow me on medium, twitter, github share with your friends 😎


Published by HackerNoon on 2018/05/14