-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f184b12
commit 799b179
Showing
1 changed file
with
77 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} |