libnick 2024.12.0
A cross-platform base for native Nickvision applications.
Loading...
Searching...
No Matches
Defining Events In Your Classes

libnick events are designed to easily integrate within your classes to easily notify consumers of changes in state of an object.

Let's take a look at Nickvision::App::DataFileBase and how it defines and uses events.

namespace Nickvision::App
{
class DataFileBase
{
public:
...
Events::Event<Events::EventArgs>& saved()
{
return m_saved;
}
bool save()
{
...
saved({}); //Same as saved.invoke({});
...
}
private:
...
Events::Event<Events::EventArgs> m_saved;
};
}
Events::Event< Events::EventArgs > & saved()
Gets the Saved event.
bool save()
Saves the config file to disk.
Definition appinfo.h:32

Here we can see how Nickvision::App::DataFileBase defines a saved event, exposes it to the consumer, and triggers/invokes the event within its save method.

A consumer of Nickvision::App::DataFileBase can easily subscribe to the event and have its handler called when the configuration object is saved:

using namespace Nickvision::App;
using namespace Nickvision::Events;
void handler(const EventArgs& e)
{
std::cout << "Config saved." << std::endl;
}
int main()
{
DataFileBase base{ ... };
base.saved() += handler;
base.save();
}
A base class for json data files.
Definition datafilebase.h:37
A base class for event arguments.
Definition eventargs.h:32
Definition event.h:34

This program will print Config saved. as a result of the event being invoke once the save method was called.