Blogging

Modular Javascript #4 – PubSub Javascript Design Pattern

Modular Javascript #4 – PubSub Javascript Design Pattern
Written by techmanish

Last video, we covered the revealing module pattern – where we expose an API allowing modules to talk to each other. This works well for smaller amounts of modules, but can have issues when many modules need to talk to each other.

Here’s the pubsub code I’m using in this example: https://gist.github.com/learncodeacademy/777349747d8382bfb722

In this video, we’ll cover the pubsub design pattern (publish/subscribe), which allows us to decouple our modules. Once integrated with our pubsub module, they can emit events and not have to worry about which modules depend on them. Modules can subscribe to events and be notified when any module publishes.

About the author

techmanish

20 Comments

  • Very good tutorial ,
    thanks!!!!!!
    ƪ(˘⌣˘)┐ ƪ(˘⌣˘)ʃ ┌(˘⌣˘)ʃƪ(˘⌣˘)┐ ƪ(˘⌣˘)ʃ ┌(˘⌣˘)ʃƪ(˘⌣˘)┐ ƪ(˘⌣˘)ʃ ┌(˘⌣˘)ʃ

  • Thank you so much for the tutorial, JS suddenly makes a lot of sense to me. I can now say good bye to spaghetti codes! Thank you, you're awesome!

  • im starting to see the need for frameworks like react with all these modules wanting to know what the other module is doing and when to update etc. interesting stuff!

  • Holy smoke I wish I had learned all of this before learning any javascript framework. Still love React, but now everything just make more sense.

  • I don't understand why the functions are pushed into a list of event handlers within the pubsub module. Aren't we overcomplicating the supposedly simple and "stupid" pubsub module by pushing all these events into a collection? Wouldn't it be more efficient to just have services subscribe to to these events, and then have the pubsub simply send out notifications that the event happened, and then let the services appropriately handle that event internally?

    My concern is that as the handlers get more and more complex, wouldn't it be better to spread out the load? Let's say there are 50 subscribers to one event, and each of the handlers within those services needs to run 5 functions on average when that event happens. Do we want to run 250 functions within the pubsub service, or send out 50 simple requests to the services to let them know the event was triggered, and have them all execute their handlers individually?

Leave a Reply

%d bloggers like this: