use std::{
collections::HashMap,
sync::{Arc, Mutex},
};
type EventHandle<T> = Box<dyn Fn(T) + Send + Sync>;
pub struct EventEmitter<T> {
listeners: Arc<Mutex<HashMap<String, Vec<EventHandle<T>>>>>,
}
impl<T> EventEmitter<T> {
pub fn new() -> Self {
Self {
listeners: Arc::new(Mutex::new(HashMap::new())),
}
}
pub fn on<F>(&mut self, event: &str, handler: F)
where
F: Fn(T) + Send + Sync + 'static,
{
let mut listeners = self.listeners.lock().unwrap();
listeners
.entry(event.to_string())
.or_default()
.push(Box::new(handler))
}
pub fn emit(&self, event: &str, data: T)
where
T: Clone,
{
let listeners = self.listeners.lock().unwrap();
if let Some(handlers) = listeners.get(event) {
for cb in handlers {
cb(data.clone())
}
}
}
pub fn once<F>(&mut self, event: &str, mut handler: F) {
unimplemented!("Need using id to identify");
}
}