use crate::utilities::{HandlerList, HandlerSnapshot};
use std::rc::Rc;
pub struct Event<A: ?Sized> {
handlers: HandlerList<dyn Fn(&A)>,
}
impl<A: ?Sized> Default for Event<A> {
fn default() -> Self {
Self::new()
}
}
impl<A: ?Sized> Event<A> {
pub fn new() -> Self {
Self { handlers: HandlerList::new() }
}
pub fn with_shared_ids(ids: std::rc::Rc<std::cell::Cell<u64>>) -> Self {
Self { handlers: HandlerList::with_shared_ids(ids) }
}
pub fn with_ordered_ids() -> Self {
Self { handlers: HandlerList::with_ordered_ids() }
}
pub fn snapshot(&self) -> HandlerSnapshot<dyn Fn(&A)> {
self.handlers.snapshot()
}
pub fn add(&self, handler: Rc<dyn Fn(&A)>) -> u64 {
self.handlers.add(handler)
}
pub fn remove(&self, token: u64) -> bool {
self.handlers.remove(token)
}
pub fn has_handlers(&self) -> bool {
!self.handlers.is_empty()
}
pub fn handler_count(&self) -> usize {
self.handlers.len()
}
pub fn raise(&self, args: &A) {
if self.handlers.is_empty() {
return;
}
for (_, handler) in self.handlers.snapshot().iter() {
handler(args);
}
}
}