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