From 210a04650e6b7f1d718240195a78c66e1783a1c3 Mon Sep 17 00:00:00 2001 From: LordMidas <55047920+LordMidas@users.noreply.github.com> Date: Fri, 6 Oct 2023 22:17:22 -0400 Subject: [PATCH] feat: add MSU.Class.Event class This emulates event listeners. Now someone can raise an event without having to know who is listening to the event. --- msu/classes/event.nut | 72 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 msu/classes/event.nut diff --git a/msu/classes/event.nut b/msu/classes/event.nut new file mode 100644 index 000000000..f241afbeb --- /dev/null +++ b/msu/classes/event.nut @@ -0,0 +1,72 @@ +::MSU.Class.Event <- class +{ + __Functions = null; + + constructor() + { + this.__Functions = []; + } + + function register( _env, _function ) + { + // ::MSU.requireFunction(_function); + foreach (i, funcInfo in this.__Functions) + { + if (funcInfo[1] == _function) + { + return; + } + } + + this.__Functions.push([_env, _function]); + } + + function unregister( _function ) + { + // ::MSU.requireFunction(_function); + foreach (i, funcInfo in this.__Functions) + { + if (funcInfo[1] == _function) + { + this.__Functions.remove[i]; + return; + } + } + + throw ::MSU.Exception.KeyNotFound(_function); + } + + function invoke( _argsArray = null ) + { + if (_argsArray == null) _argsArray = [null]; + else _argsArray.insert(0, null); + + foreach (funcInfo in this.__Functions) + { + _argsArray[0] = funcInfo[0]; + funcInfo[1].acall(_argsArray); + } + } + + // Will iterate over every registered function and check _conditionFunction + // if _conditionFunction returns false, stops iteration immediately + function conditionalInvoke( _conditionFunction, _argsArray = null ) + { + if (_argsArray == null) _argsArray = [null]; + else _argsArray.insert(0, null); + + foreach (funcInfo in this.__Functions) + { + if (_conditionFunction() == false) + return; + + _argsArray[0] = funcInfo[0]; + funcInfo[1].acall(_argsArray); + } + } + + function clear() + { + this.__Functions.clear(); + } +}