63 lines
1.6 KiB
C++
63 lines
1.6 KiB
C++
// Copyright (c) 2023 Dominic Masters
|
|
//
|
|
// This software is released under the MIT License.
|
|
// https://opensource.org/licenses/MIT
|
|
|
|
#pragma once
|
|
#include "StateInterfaces.hpp"
|
|
|
|
namespace Dawn {
|
|
template<typename...A>
|
|
class StateEvent : public IStateEvent {
|
|
protected:
|
|
uint32_t stateEventId = 0;
|
|
|
|
/**
|
|
* Received notification from a state owner to let this state event know
|
|
* that it wishes to unsubscribe all the event listeners that it may have
|
|
* attached to this event.
|
|
*
|
|
* @param owner State owner that is being disposed.
|
|
*/
|
|
void _stateOwnerDestroyed(IStateOwner *owner) override {
|
|
auto it = this->_eventListeners.begin();
|
|
while(it != this->_eventListeners.end()) {
|
|
if(it->owner == owner) {
|
|
it = this->_eventListeners.erase(it);
|
|
} else {
|
|
++it;
|
|
}
|
|
}
|
|
}
|
|
|
|
public:
|
|
std::vector<StateEventListener<A...>> _eventListeners;
|
|
|
|
/**
|
|
* Invokes the event and emits to all of the listeners.
|
|
*
|
|
* @param args Arguments for this event to pass to the listeners.
|
|
*/
|
|
void invoke(A... args) {
|
|
auto copy = this->_eventListeners;
|
|
auto it = copy.begin();
|
|
while(it != copy.end()) {
|
|
it->listener(args...);
|
|
++it;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Disposal of a state event.
|
|
*/
|
|
~StateEvent() {
|
|
auto it = this->_eventListeners.begin();
|
|
while(it != this->_eventListeners.end()) {
|
|
it->owner->_stateEventDisposed(this);
|
|
++it;
|
|
}
|
|
}
|
|
|
|
friend class StateOwner;
|
|
};
|
|
} |