|
1 | 1 | use std::collections::HashMap; |
2 | 2 | use std::sync::Arc; |
3 | 3 |
|
| 4 | +/// Typed event names for compile-time safety. |
| 5 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 6 | +pub enum EventName { |
| 7 | + Click, |
| 8 | + Change, |
| 9 | +} |
| 10 | + |
| 11 | +impl EventName { |
| 12 | + pub fn as_str(&self) -> &'static str { |
| 13 | + match self { |
| 14 | + EventName::Click => "click", |
| 15 | + EventName::Change => "change", |
| 16 | + } |
| 17 | + } |
| 18 | + |
| 19 | + pub fn from_str(s: &str) -> Option<Self> { |
| 20 | + match s { |
| 21 | + "click" => Some(EventName::Click), |
| 22 | + "change" => Some(EventName::Change), |
| 23 | + _ => None, |
| 24 | + } |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +impl std::fmt::Display for EventName { |
| 29 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 30 | + f.write_str(self.as_str()) |
| 31 | + } |
| 32 | +} |
| 33 | + |
4 | 34 | /// Type alias for event handler callbacks. |
5 | 35 | /// Receives the event arguments as a serde_json::Value. |
6 | 36 | pub type EventCallback = Arc<dyn Fn(serde_json::Value) + Send + Sync>; |
@@ -41,6 +71,27 @@ impl EventRegistry { |
41 | 71 | self.handlers.extend(other.handlers); |
42 | 72 | } |
43 | 73 |
|
| 74 | + /// Register a callback using a typed event name. |
| 75 | + pub fn register_typed( |
| 76 | + &mut self, |
| 77 | + widget_id: &str, |
| 78 | + event: EventName, |
| 79 | + callback: EventCallback, |
| 80 | + ) { |
| 81 | + self.register(widget_id, event.as_str(), callback); |
| 82 | + } |
| 83 | + |
| 84 | + /// Dispatch an event using a typed event name. |
| 85 | + /// Returns true if a handler was found and invoked, false otherwise. |
| 86 | + pub fn dispatch_typed( |
| 87 | + &self, |
| 88 | + widget_id: &str, |
| 89 | + event: EventName, |
| 90 | + args: serde_json::Value, |
| 91 | + ) -> bool { |
| 92 | + self.dispatch(widget_id, event.as_str(), args) |
| 93 | + } |
| 94 | + |
44 | 95 | /// Remove all registered handlers. |
45 | 96 | pub fn clear(&mut self) { |
46 | 97 | self.handlers.clear(); |
|
0 commit comments