Skip to content

Commit

Permalink
Add event system
Browse files Browse the repository at this point in the history
  • Loading branch information
LunaTheFoxgirl committed Oct 7, 2024
1 parent f184b12 commit 799b179
Showing 1 changed file with 77 additions and 0 deletions.
77 changes: 77 additions & 0 deletions source/numem/events.d
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/**
Numem events
*/
module numem.events;
import numem.collections.vector;
import numem.core.memory;

/**
An event.
*/
struct Event(T, EventData...) {
@nogc:
private:
weak_vector!EventHandlerFuncT subscribers;

public:

/**
The type of the event handler function
*/
alias EventHandlerFuncT = void function(ref T, EventData);

/**
Calls all of the event handlers
*/
auto opCall(ref T caller, EventData data) {
foreach(subscriber; subscribers) {
subscriber(caller, data);
}
}

/**
Registers a handler with the event
*/
auto opOpAssign(string op: "~")(EventHandlerFuncT handler) {
subscribers ~= handler;
return this;
}

/**
Removes a handler from the event
*/
auto opOpAssign(string op: "-")(EventHandlerFuncT handler) {
foreach(i; 0..subscribers.length) {
if (subscribers[i] == handler) {
subscribers.remove(i);
return this;
}
}
return this;
}
}

version(unittest) {
class EventTest {
Event!EventTest onFuncCalled;
bool localVar = false;

void func() {
this.onFuncCalled(this);
}
}
}

@("Event call")
unittest {

EventTest test = nogc_new!EventTest;
test.onFuncCalled ~= (ref EventTest caller) {
caller.localVar = true;
return;
};

test.func();

assert(test.localVar);
}

0 comments on commit 799b179

Please sign in to comment.