4

We use JS by the way, but I think it's language agnostic. I'm open to ideas.

We have this "pub-sub" framework that we use at work to fix the problem of tightly-coupled code. Works fine. Modules listen to events, things run, broadcasts events, more things run. It's amazing. However...

For instance I wanted to click on a link to open a modal, modify the passed data, and send it back to the called. Sending it to the modal would be as simple as broadcasting an event with the data. Modal, subscribed to the event, responds and does some alteration to the data. The problem is getting the data back to the caller.

Scenarios:

  • Module broadcasts an event, and at the same time listens to an event in the hopes of a response (event from another module). How would I know that the response was in effect of the event that was broadcast just before it?

  • Another is that I plan to send out a callback function with the data sent through the event. That way, the receivers can just call the callback with the data from their side. However, the module would be receiving an unknown amount of callback calls, depending on how many subscribers.

The scenario is more of directed messaging, which is somewhat contradictory to the fire-and-forget nature of a broadcast. Are there any patterns which still maintains loose coupling, modularity and the "unknown to the other" type of architecture?

1

You're basically using a mediator pattern. To start, be aware that you might be overusing it if you're using it everywhere. Event driven programs can be harder to debug or to even reliably predict behavior, so you'll want to use this pattern only when there's an actual pain caused by the normal coupling. For a modal I very much doubt I'd use it.

With that said if you still want to go ahead with this, there's nothing wrong with having a publisher listen on a new unique event and then send information about what event it's listening on when it publishes. That way the receiver knows what event to trigger, and since it's unique the publisher knows who it's from when it receives the event. What you are doing in effect is creating a private event used only once by the publisher and the subscriber.

If instead you want to go with the callback type solution, consider investigating javascript promises. Rather than saying "here's a function you should execute when you're done", promises say "tell me when you're done and I'll decide what to do".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.