cc-haxe/src/util/EventBus.hx

62 lines
1.4 KiB
Haxe
Raw Normal View History

2021-12-20 00:55:30 +00:00
package util;
import util.Signal.SignalListner;
class EventBusListner<T> {
@:allow(util.EventBus)
private final signalListner:SignalListner<T>;
@:allow(util.EventBus)
private final eventName:String;
@:allow(util.EventBus)
private function new(signalListner: SignalListner<T>,eventName: String) {
this.signalListner = signalListner;
this.eventName = eventName;
}
}
/**
Generic event handler.
**/
class EventBus<T>{
private var listner: Map<String,Signal<T>> = new Map();
public function new() {
}
public function on(eventName: String, callback: T->Void):EventBusListner<T>{
if (!listner.exists(eventName)){
listner[eventName] = new Signal();
}
var signalListner = listner[eventName].on(callback);
return new EventBusListner(signalListner,eventName);
}
public function once(eventName: String,callback: T->Void):EventBusListner<T> {
if (!listner.exists(eventName)){
listner[eventName] = new Signal();
}
var signalListner = listner[eventName].once(callback);
return new EventBusListner(signalListner,eventName);
}
public function emit(eventName: String, data: Any) {
if (listner.exists(eventName)){
var signal = listner[eventName];
signal.emit(data);
}
}
public function removeListner(id: EventBusListner<T>) {
if (!listner.exists(id.eventName)) {
return;
}
listner[id.eventName].remove(id.signalListner);
}
}