Unlimited WordPress themes, graphics, videos & courses! Unlimited asset downloads! From $16.50/m
Js design 1
  • Overview
  • Transcript

3.1 The Publisher/Subscriber Pattern

Often called the "Pub/Sub" pattern, this pattern allows us to reduce the coupling between different parts of our application by allowing components to communicate without direct dependencies.

3.1 The Publisher/Subscriber Pattern

Hi, folks. In this lesson, we're going to look at the Publisher/Subscriber Pattern or Pub/Sub as it's usually named. This pattern allows us to create modules that do not depend on each other, but can still communicate indirectly. This pattern is great for decoupling different parts of our application. Pubsub is another very common pattern that you're likely to run across frequently. It's a useful pattern, but it is easy to overuse it. Not all coupling is bad. So, using Pub/Sub to the point where no module depends on any other module in the system can lead to confusion and harder to maintain code. But in small systems or when used wisely, Pub/Sub can be beneficial. So let's take a look at how it can be implemented in JavaScript. Let's create a new folder in the JS folder. I'm gonna call this one Pub/Sub and then inside this folder, let's create a new AMD module called pubsub.js. The Pub/Sub module will return the methods publish and subscribe and we'll need an object in which to store registered callbacks or subscribers. It makes sense to look at the subscribe function first, which is the method that other modules will use to register a callback with. It will accept two arguments, the topic or event name to subscribe to and the callback function to invoke when the topic is published. Inside this method, we first need to check to see whether the topic being registered already exists. If it doesn't, we can create it as an array. So we just check whether the subscribers.topic is faulty, we use the bracket notation instead of the dot notation, because we're working with a parameter. And if it is faulty, we just create the topic and initialize it to an empty array. Lastly, we can just push the callback into the array. So lets now add the publish method. This method will receive the topic to publish and, optionally, it may receive some data to pass to the subscribers. So first of all, we can just check whether there are any registered subscribers for the topic that is being published. If there aren't any subscribers, it's not worth actually publishing. Next, we can just iterate the array for the topic, invoking any subscribers and passing through any data that may have been provided to the published method. We can use the for each method to iterate the array. The callback function passed to the for each method will be invoked for each callback in the array, which we just invoke and pass through the data. So now let's add two new modules, they'll both depend on the Pub/Sub module. But importantly, they won't depend on each other. They don't even need to know about each other. So let's add a new module to the Pub/Sub folder. We'll just call this one module A. We're going to need the Require function inside this module. And first of all, we can just load the Pub/Sub module. So let's use the subscribe method to subscribe to a topic. And inside the handler function, let's just log out a message and the data. So now let's add a second module. We'll call this one Module B. And we need to use the require function here to also load up the Pub/Sub module. And let's return a method that lets us publish to the topic. So we just create a basic data object that has a single property called something, and a simple string value. And then we use the PubSub modules publish method to publish to the topic called Atopic and we can pass through our simple data object. Great. So now, let's add the init file for this lesson. All we need to do is lord our two modules And then we can use the publish event method of Module B to publish the event. So lastly, lets just update the main.js file to load our new init module for this example And now let's go back to the browser and we should be able to use our run example method to run the Pub/Sub example. So as you can see, we see the message in the console to say that A topic was published and it was passed a data object. Now we can't actually see inside that data object, I'm not sure why that is. But if we were to change that to get the property, I think we would probably see that. In order to fully satisfy the Pub/Sub contract, we usually need to provide a way for subscribers to unsubscribe from further broadcasts. A great way to handle the disposal of subscriptions is to provide a dispose method on an object returned when the subscribe method is used. To remove a subscription, we first need to know what the index of the callback in the array is so that we can remove it. We can collect this information when we subscribe. We first, need to add an index variable to the subscribe method in the Pub/Sub module. We can use the return value of the push method to get the index. The push method returns the new length of the array, so we can just subtract one from this to get the index of the callback that we just added. Now we need to return an object from the subscribe method that exposes a dispose method. What we do in the dispose method is splice out the callback from the array of subscribers for that topic. To see the disposal in action, we can have the main.js file publish the event twice. To see the disposal in action, we can have the init.js file publish the event twice. Let's go back to the browser now and we should find we received the console log twice. If we change the way that Module A subscribes, however. Let's just add a new variable, which we can call subscription and we can populate this with the method that gets returned from the subscribe method And then inside the handler, let's just invoke this new dispose method. So what should happen now is that the first time the topic is published, the subscription should get disposed in the handler. So we should now only see the console log once. Let's go back to the browser and just verify that that is happening. So in this lesson, we looked at a simple implementation of the Pub/Sub pattern in JavaScript. Our Pub/Sub module exposes two methods, publish and subscribe. The publish method is used to notify subscribers that something has occurred and this communication takes place over a named channel, also known as a topic. The subscribe method allows modules to subscribe to these notifications or events as they're also called and register a callback that will be invoked when the event is published. We also saw how we can easily pass through data to these callbacks when they are invoked. We also saw that we can provide a dispose method that allows subscribers to unregister from further notifications. This method is passed back to the code that creates the subscription, so it's easy for code to clean up after itself when it's done. As we've seen, one of the main advantages of the Pub/Sub pattern is that it allows us to keep our modules loosely coupled. This is good, but don't forget that it can make the relationships between different parts of our application more obscure, so it's very easy to overuse. Thanks for watching.

Back to the top