use std::collections::HashMap; use wasm_bindgen::prelude::*; use rmpv::Value; #[wasm_bindgen] pub struct Hooks { events: HashMap> } impl Hooks { pub fn new() -> Self { Self { events: HashMap::new() } } pub fn on(&mut self, event: String, callback: F) where F: Fn(&Value) + 'static + Send + Sync { self.events.entry(event) .or_insert_with(Vec::new) .push(Hook::new(callback, false)); } pub fn once(&mut self, event: String, callback: F) where F: Fn(&Value) + 'static + Send + Sync { self.events.entry(event) .or_insert_with(Vec::new) .push(Hook::new(callback, true)); } pub fn emit(&mut self, event: String, data: &Value) { if let Some(event_list) = self.events.get_mut(&event) { for event in event_list.iter_mut() { event.call(data); } } } } #[wasm_bindgen] pub struct Hook { func: Box () + Sync + Send>, once: bool, called: bool } impl Hook { pub fn new(callback: F, once: bool) -> Self where F: Fn(&Value) -> () + 'static + Send + Sync { Self { func: Box::new(callback), once, called: false } } pub fn call(&mut self, data: &Value) { if self.once { if !self.called { (self.func)(data); self.called = true; } } else { (self.func)(data); } } }