Decouple your code with this one trick!
While this applies to javascript, most languages have their own equivalents.
Don’t you love when you need to inject that reference to a random object, that that you want to to notify? And then you change something in the implementation and all hell breaks loose because another file on a totaly different directory now needs to be refactored? Of course you don’t. None of us do. That’s why slowly but surely the whole programming world has been shifting from inheritence to composition. The decoupled code is simply to easy to maintain to resist. That’s why today we’re going to shill a little piece of software that replaces events and listeners. There are many implementations, but we chose to use pubsub-js. But the basic architectural pattern is the same. Internally it’s basically a blackboard with a list of topics (sometimes called “channels”). Anyone can subscribe to any topic and anyone can listen for new messages. This way a global reference to a PubSub object is enough anywhere at anytime. But it’s better to see the code than to talk about concepts. Let’s dive in:
import PubSub from 'pubsub-js'
PubSub.subscribe('connection', (message, data) => {
const client = data;
alert(`A new client has connected with an id of ${client.id}`);
});
// This subscriber will listen for "connection" topic and when a new connection is opened will alert the user
// Both pieces of code can be in a different file or module!
server.addConnectionListener((connection) => {
Pubsub.publish('connection', {
id: connection.id,
name: `User#${connection.name}`
});
});
Both pieces of code needn’t have any knowledge of one another. And of course you can have many listeners and many publishers to the same topic.