Broadcasting message containing custom data?

I want to send messages containing custom data to X amount of “unknown” listeners (i.e. global broadcast to all classes interested in listening to those messages). juce::Message class seems to be designed for this kind of data, but if I understand the documentation correctly, there is an issue there:

Am I right that MessageListener’s postMessage() sends the message only to itself? If this is the case, how do I send the message to X amount of other/unknown classes?

juce::Message probably isn’t necessary for this. You could simply create a singleton class through which other objects can listen for and post messages.

class GlobalMessages
{
public:
    struct Listener
    {
        virtual ~Listener() = defaultl

        virtual void handleMessage (const juce::String& message) = 0;
    };

    GlobalMessages() = default;

    ~GlobalMessages()
    {
        clearSingletonInstance();
    }

    static void post (const juce::String& message)
    {
        getInstance()->m_listeners.call([&message] (Listener& l) {
            l.handleMessage (message);
        });
    }

    JUCE_DECLARE_SINGLETON (GlobalMessages, false)

private:
    juce::ListenerList<Listener> m_listeners;
};

JUCE_IMPLEMENT_SINGLETON (GlobalMessages)

// ====

GlobalMessages::post ("Hello, World!");

Untested but something along those lines will probably work. Add any additional post methods you need for different types of messages, and corresponding handler methods in the listener.


Please don’t do this.

Wanting to send messages to anywhere and everywhere in your app is almost always a red flag. It would be way too easy for the wrong thing to post the wrong message and your whole app is broken.

A much better solution would be to pass around the actual object that wants to be listened to so you can strictly control access to what objects can post and handle messages.

The mediator pattern is useful for this: Mediator

The MVP pattern is also extremely useful for having one centralised object (the model) manage events happening in your app: GUI Architectures

1 Like

I had something similar to a mediator in mind. But instead of having a mediator interface class pointer passed to other classes, I would have used a message for the communication. I think I was overthinking the problem. I’ll go with the mediator instead.

Thank you!