Treehopper C++ API
Event< Sender, EventArgs > Class Template Reference

Provides a simple C#-style observer pattern event queue. More...

#include <Event.h>

Public Member Functions

 Event (Sender &sender)
 Create a new Event that belongs to a Sender, and takes an EventArgs event object type. More...
size_t getAddress (std::function< void(Sender &, EventArgs &)> f)
void operator+= (function< void(Sender &sender, EventArgs &e)> handler)
 Subscribe to an event. More...
void operator-= (function< void(Sender &sender, EventArgs &e)> handler)

Detailed Description

template<class Sender, class EventArgs>
class Treehopper::Event< Sender, EventArgs >

This class provides two public operators – Event::operator+= and Event::operator-= – which allows user code to subscribe and unsubscribe from these events.

For example, to subscribe to the Pin::pinChanged event using a lambda expression,

board.pins[4].pinChanged += [](DigitalIn& sender, PinChangedEventArgs& e) {
cout << "Pin 4 event: " << e.newValue << endl;

You may also subscribe to events by passing regular named functions, i.e.:

void pinHandler(DigitalIn& sender, PinChangedEventArgs& e) {
cout << "Pin 4 event: " << e.newValue << endl;
void setup() {
board.pins[4].pinChanged += pinHandler;

If you wish to unsubscribe to an event, pass the same function to Event::operator-=:

void done() {
board.pins[4].pinChanged -= pinHandler;

Note that for proper binding (and unbinding), the method signature must match precisely (i.e., both parameters must be passed by reference).

This is all that is needed to consume events; if you wish to use this class in your own code to publish events, start by creating an EventArgs struct with all the parameters you wish to pass to subscribers. By convention, we use the suffix "EventArgs" in the name of the struct, however this is not required:

struct ReadingReceivedEventArgs
double newValue;

Next, add an Event member to your class:

class MyClass
Event<MyClass, ReadingReceivedEventArgs> readingReceived;

When you actually want to fire an event, use the Event::invoke() method:

ReadingReceivedEventArgs event;
event.newValue = getData();

Constructor & Destructor Documentation

◆ Event()

Event ( Sender &  sender)
[in]senderThe parent object that fired this event.

Member Function Documentation

◆ getAddress()

size_t getAddress ( std::function< void(Sender &, EventArgs &)>  f)

◆ operator+=()

void operator+= ( function< void(Sender &sender, EventArgs &e)>  handler)

◆ operator-=()

void operator-= ( function< void(Sender &sender, EventArgs &e)>  handler)

The documentation for this class was generated from the following file: