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{ private var listner: Map> = new Map(); public function new() { } public function on(eventName: String, callback: Callback):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):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(); } }