I really like the signal API from AS3 and use it all the time. I even ported it to Swift, JS and Dart in order to apply it in other environments. To use signals in HaxeFlixel you just need to define an object, that will represents your signal, and its callback type. So, for example, if you want to make a signal, that will need one String, you have to create a signal like that:
To use it you need to call dispatch
method:
In order to receive this message you need to add a listener (callback). Signal’s listener is a function that will be triggered, when method dispatch
is called. Signature of a callback and a signal’s signature must be equal. So if you created a signal, that sends 1 String, you need a callback, that will accept 1 String.
A callback for the previous signal will be:
There are 2 possibilities to add a listener to a signal. You can attach it permanently using code
or you can add it only for a one trigger using a function
Method addOnce
is a shortcut for the removing a listener after the first received message.
To remove a listener from a signal you need to use
Alternatively you can remove all listeners from a signal by calling method removeAll()
.
In order to add more parameters to your signal, you can add them in the signature. For example, this signal will send a String and an object of type Dynamic
You can also create a signal without parameters by using shortcut class:
It works exactly like FlxTypedSignal, just without any parameters.
As all other HaxeFlixel objects you can destroy a signal using
if it is not needed anymore.
P.S At the moment (Version 3.3.12) FlxDestroyUtil.destroy
doesn’t work on signals (see more here), also a manual way doesn’t work
so you have to remove your listeners using a method removeAll()
, if you don’t need them anymore.
More information about HaxeFlixel Signals you can find on Cheat Sheet, documentation or in source.
One side note, if you are new to Signals. Compared to events, signals are dispatched synchrony, that means your callbacks will be trigged instantly after dispatch()
is called. Take it into account, as you can get some very wild behaviors, if you use signals improperly.
Happy coding :)