...

Elementor #2076

by Ballistic Freaks

Share our post:

Share on facebook
Share on linkedin
Share on twitter
Share on email

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.

Other articles by us:

Elementor #2076

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

Read More »

REFER FREAKS

GET 20% BACK

Create a code for your friends to use and get back 10% of every successful transaction that used your code. Same code can be used multiple times!

Code already taken!

Note: Referral code will be tied to the wallet used to create it. After every successful mint, your wallet will automatically receive 20% of mints value

code creation fee:

0.02 ETH

Seraphinite AcceleratorBannerText_Seraphinite Accelerator
Turns on site high speed to be attractive for people and search engines.