I need to send messages from a child component to its parent.
Reading up, it appears I have {Action/Change}(Broadcaster&Listener), where Change accumulates messages and sends a batch every 'tick', whereas Action works instantly. So for my case I want Action.
This is what I've got:
Sender.hpp
class Sender: public Component, private ActionBroadcaster
{
private:
void send(int data) { sendActionMessage(String(data)); }
}
mainComponent.cpp
#include "Sender.h"
class MainContentComponent : public Component, private ActionListener
{
ScopedPointer<Sender> pSender;
public:
MainContentComponent()
{
pSender = new Sender();
addAndMakeVisible(pSender);
pSender->addActionListener(this);
}
private:
// event from Sender
void actionListenerCallback(const String& message) {
int val = message.getIntValue();
}
It works, but is it the correct approach?
A couple of things worry me:
- What if I wish to send more information? Must I manually serialise and deserialise it into a String?
- What if my main component is listening for three different message-sending-components? They are all going to trigger the same callback, aren't they! Does this mean I would need to encode the sender in the string, and extract it and branch accordingly inside the handler?
An alternative architecture might be:
class Targ {
void fromA(int data) {...}
void fromB(int data) {...}
Targ() {
A.addHandler(& this->fromA );
B.addHandler(& this->fromB );
That would let me name a handler for each type of message, which might result in clearer code, although now I quite like the idea of having all the message handling occur in one place.
π
