Introduction

In 2020 talking about “plain JavaScript” may sound weird. We have TypeScript and we have a lot of libraries and excellent frameworks such as Angular, React and so on.

But truth is that from time to time, as a professional software engineer, you’ll find yourself working on a legacy web application that doesn’t use any framework on the frontend side. The only friendly-looking thing you’ll find (sometimes) will be jQuery. That’s it.

However you’ll still have to implement a good solution, hopefully structuring frontend in components, decoupling frontend from backend, writing JS modules to function as sort of view-models for your UI components. And while doing this you’ll need to use some sort of “communication protocol” to make these components work together well and talk each other.

I’ve recently been in this situation and one of the first things I did was implementing a Messaging Service JavaScript module to handle communication between components implementing the Messaging Pattern, more specifically the publish/subscribe messaging pattern.

In this article I’ll show you the (very simple) code and I’ll explain how it works and the choices I made.

GitHub Repository

If you need the ready-made solution and you prefer to inspect the code by yourself, here’s the GitHub repository with the code: feel free to use it as you like.

You’ll find the module’s source code in the ./services/messaging-service.js file.

The Messaging Service Module

To build a basic messaging service we need at least three main functions:

  • Subscribe
  • Publish
  • [Optional] Unsubscribe

The Subscribe Function

This is the function that components will call to register themselves to be notified whenever a specific topic will be published.

In order to register, components need to provide information on:

  • Who they are
  • The topic they’re interested in
  • What they’re going to do when something will be published about the topic

The Publish function could look something like this…

#javascript #front-end-development

How to Implement a Messaging Service in JavaScript
26.55 GEEK