Pub/Sub JavaScript Pattern

I've been feeling pretty awesome refactoring my spaghetti code into modular code using the module and prototype patterns into my projects. But I still can't shake this 'dirty' feeling with how my code is written.

Although my code is now organized and modular, it still feels tangled and tightly coupled to many other portions of the codebase.

After a bit more reading I came across the Publish/Subscribe (Observer) pattern and this seems to be the answer to my problem.

Here's another JavaScript patterns brain dump.

So far I've been using Morgan Roderick's PubSubJS library to implement Pub/Sub communication in my code: https://github.com/mroderick/PubSubJS

Decoupling Code

Code is tightly coupled when objects directly call the methods of other objects. Instead, the pub/sub pattern allows a dependent object to 'subscribe' to a specific event of another object and is notified when the event occurs.

One of the main goals of the pub/sub pattern is to avoid dependencies between the subscriber and the publisher.

Pub/Sub allows code to be decoupled and broken down into smaller, loosely coupled modules. When an event is published, a notify message is sent out. All the subscribed observers receive the message and can invoke their callbacks.

Essentially, publishers notify subscribers when events occur.

Subscribers can listen to these notifications and execute code in response to the event.

Encouraging Reusable Modules

With loosely coupled code, each component of the system is only concerned with it's own responsibility and doesn’t care directly about the logic of any other components.

This allows for easy reuse of different modules since modules are not directly coupled with the interfaces of other modules.

Duncan Leung

Front End Developer at iHerb.com

Irvine, CA

Subscribe to Duncan Leung: Javascript and Front End Development

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!