Skip to main content

topcoat_runtime/
event_handler.rs

1use topcoat_core::context::Cx;
2use topcoat_view::{Attribute, AttributeKeyViewParts, AttributeViewParts, PartsWriter, Unescaped};
3
4use crate::{Event, Expr};
5
6pub trait EventHandlerFn {}
7
8impl<T, R> EventHandlerFn for T where T: Fn(Event) -> R {}
9
10/// An event handler attribute. Emits a JavaScript closure expression into a
11/// `data-topcoat-on:<event>` attribute on the element. The browser scanner
12/// wraps it in `new Function('__cx', ...)` to obtain a real handler.
13pub struct EventHandler<K, F> {
14    key: K,
15    value: Expr<F>,
16}
17
18impl<K, F> EventHandler<K, F>
19where
20    F: EventHandlerFn,
21{
22    #[inline]
23    pub fn new(key: K, value: Expr<F>) -> Self {
24        Self { key, value }
25    }
26}
27
28impl<K, F> AttributeViewParts for EventHandler<K, F>
29where
30    K: AttributeKeyViewParts,
31{
32    #[inline]
33    fn into_view_parts(self, cx: &Cx, parts: &mut PartsWriter<'_>) {
34        Attribute::new(
35            (Unescaped::new_unchecked("data-topcoat-on:"), self.key),
36            self.value.js,
37        )
38        .into_view_parts(cx, parts);
39    }
40}