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.
So far I've been using Morgan Roderick's PubSubJS library to implement Pub/Sub communication in my code: https://github.com/mroderick/PubSubJS
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.