cc-haxe/src/util/EventBus.hx
2022-02-21 01:50:19 +01:00

61 lines
1.3 KiB
Haxe

package util;
using tink.CoreApi;
class EventBusListner {
@:allow(util.EventBus)
private final link:CallbackLink;
@:allow(util.EventBus)
private final eventName:String;
@:allow(util.EventBus)
private function new(link: CallbackLink,eventName: String) {
this.link = link;
this.eventName = eventName;
}
}
/**
Generic event handler.
**/
class EventBus<T>{
private var listner: Map<String,SignalTrigger<T>> = new Map();
public function new() {
}
public function on(eventName: String, callback: Callback<T>):EventBusListner{
if (!listner.exists(eventName)){
listner[eventName] = Signal.trigger();
}
var link = listner[eventName].asSignal().handle(callback);
return new EventBusListner(link,eventName);
}
public function once(eventName: String,callback: Callback<T>):EventBusListner {
if (!listner.exists(eventName)){
listner[eventName] = Signal.trigger();
}
var link = listner[eventName].asSignal().handle(callback);
return new EventBusListner(link,eventName);
}
public function emit(eventName: String, data: T) {
if (listner.exists(eventName)){
var trigger = listner[eventName];
trigger.trigger(data);
}
}
public function removeListner(id: EventBusListner) {
if (!listner.exists(id.eventName)) {
return;
}
id.link.cancel();
}
}