Skip to main content

euv_core/reactive/event_bus/
impl.rs

1use super::*;
2
3/// Typed cross-component event emission and scoped subscription for `EventBus`.
4impl EventBus {
5    /// Emits a typed custom event `E` to all active cross-component listeners (frozen listeners coalesce until resumed).
6    ///
7    /// # Arguments
8    ///
9    /// - `ErrorType` - Custom event payload implementing `CustomEvent`.
10    pub fn emit<ErrorType>(event: ErrorType)
11    where
12        ErrorType: CustomEvent,
13    {
14        let id: SignalId = with_runtime(
15            |runtime_ref: &mut ReactiveRuntime| runtime_ref.ensure_event_channel::<ErrorType>(),
16            SignalId::default(),
17        );
18        let channel: Signal<(u64, Option<ErrorType>)> = Signal::from_raw_id(id);
19        let _: bool = {
20            if let Some(mut updated_value) = channel.try_get_untracked() {
21                {
22                    let slot: &mut (u64, Option<ErrorType>) = &mut updated_value;
23                    slot.0 = slot.0.wrapping_add(1);
24                    slot.1 = Some(event);
25                }
26                channel.set(updated_value)
27            } else {
28                false
29            }
30        };
31    }
32
33    /// Subscribes a scope-owned listener invoked whenever custom event `E` is emitted across any component or page.
34    ///
35    /// # Arguments
36    ///
37    /// - `CallbackFn` - Event handler receiving `&E` (automatically cleaned up on unmount and paused during `PageRetention::Freeze`).
38    ///
39    /// # Returns
40    ///
41    /// - `Effect` - Scope-owned subscription effect handle.
42    #[must_use]
43    pub fn on<ErrorType, CallbackFn>(mut handler: CallbackFn) -> Effect
44    where
45        ErrorType: CustomEvent,
46        CallbackFn: FnMut(&ErrorType) + 'static,
47    {
48        let id: SignalId = with_runtime(
49            |runtime_ref: &mut ReactiveRuntime| runtime_ref.ensure_event_channel::<ErrorType>(),
50            SignalId::default(),
51        );
52        let channel: Signal<(u64, Option<ErrorType>)> = Signal::from_raw_id(id);
53        let seen_seq: Rc<Cell<u64>> = Rc::new(Cell::new(channel.get_untracked().0));
54        Effect::new(move || {
55            let (seq, payload): (u64, Option<ErrorType>) = channel.get();
56            if seq != seen_seq.replace(seq)
57                && let Some(ui_event) = payload.as_ref()
58            {
59                handler(ui_event);
60            }
61        })
62    }
63}