1
0
Fork 0

callbacks for the method to trigger

This commit is contained in:
Kevin Matz 2023-04-23 19:30:51 -04:00
parent 913a1f789b
commit 7a25eeada7
2 changed files with 37 additions and 1 deletions

View File

@ -144,7 +144,7 @@ bool Method::dispatch(std::list<std::string> patterns, const std::shared_ptr<Mes
return false;
if (matchesName(name)) // accept the message
{
/// \todo do somthing with the message
trigger(msg); // pass it along
return true;
}
}
@ -175,4 +175,32 @@ bool Method::dispatch(std::list<std::string> patterns, const std::shared_ptr<Mes
return false; // reject the message
}
/**
* @brief Method::onTrigger
* @param cb
* @return
*/
std::shared_ptr<void> Method::onTrigger(const std::function<void(std::shared_ptr<Message>)> cb)
{
// wrap the callback with a shared pointer
auto sp = std::make_shared<std::function<void(std::shared_ptr<Message>)>>(std::move(cb));
// add callback to list (as a weak pointer)
cb_trigger.push_back(sp);
// return token that caller must keep throughout it's scope
return sp;
}
/**
* @brief Method::trigger
* @param msg
*/
void Method::trigger(std::shared_ptr<Message> msg) const
{
for (const auto &wp: cb_trigger)
if (auto sp = wp.lock()) // the owner is still holding the token
(*sp)(msg);
}
} // namespace OSC

View File

@ -24,6 +24,7 @@
#pragma once
#include "message.h"
#include <functional>
#include <list>
#include <string>
@ -51,10 +52,17 @@ public:
bool dispatch(std::list<std::string> patterns, const std::shared_ptr<Message> msg) const;
std::shared_ptr<void> onTrigger(const std::function<void(std::shared_ptr<Message>)>);
protected:
void trigger(std::shared_ptr<Message>) const;
private:
Method *parent_;
std::vector<Method*> children_;
std::string name_;
std::vector<std::weak_ptr<const std::function<void(std::shared_ptr<Message>)>>> cb_trigger;
};
} // namespace OSC