Skip to main content

ferrijs_std/events/
custom_event.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3use rquickjs::{prelude::Opt, Ctx, IntoJs, Null, Result, Value};
4
5use crate::utils::object::ObjectExt;
6
7#[rquickjs::class]
8#[derive(rquickjs::class::Trace, rquickjs::JsLifetime)]
9pub struct CustomEvent<'js> {
10    event_type: String,
11    detail: Option<Value<'js>>,
12}
13
14#[rquickjs::methods]
15impl<'js> CustomEvent<'js> {
16    #[qjs(constructor)]
17    pub fn new(event_type: String, options: Opt<Value<'js>>) -> Result<Self> {
18        let mut detail = None;
19        if let Some(options) = options.0 {
20            if let Some(opt) = options.get_optional("detail")? {
21                detail = opt;
22            }
23        }
24        Ok(Self { event_type, detail })
25    }
26
27    #[qjs(get)]
28    pub fn detail(&self, ctx: Ctx<'js>) -> Result<Value<'js>> {
29        if let Some(detail) = &self.detail {
30            return Ok(detail.clone());
31        }
32        Null.into_js(&ctx)
33    }
34
35    #[qjs(get, rename = "type")]
36    pub fn event_type(&self) -> String {
37        self.event_type.clone()
38    }
39}