From 799b1798d1aa5cb3509217ac52dfdd19ddc48d9d Mon Sep 17 00:00:00 2001 From: Luna Date: Mon, 7 Oct 2024 11:22:27 +0200 Subject: [PATCH] Add event system --- source/numem/events.d | 77 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 source/numem/events.d diff --git a/source/numem/events.d b/source/numem/events.d new file mode 100644 index 0000000..9459594 --- /dev/null +++ b/source/numem/events.d @@ -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); +} \ No newline at end of file