Skip to main content

exotic

Attribute Macro exotic 

Source
#[exotic]
Expand description

An attribute for implementing exotic methods for a class.

This attribute can be added to a impl block which implements methods for a type which uses the class attribute to derive JsClass with the exotic

§Limitations

Due to limitations in the Rust type system this attribute can be used on only one impl block per type.

§Item options

Each item of the impl block must be tagged with an attribute to specify the exotic method it implements. These attributes are all in the form of #[qjs(option)].

OptionValueDescription
getFlagMakes this method the [[Get]] exotic method
setFlagMakes this method the [[Set]] exotic method
deleteFlagMakes this method the [[Delete]] exotic method
hasFlagMakes this method the [[HasProperty]] exotic method

§Example

use rquickjs::{class::Trace, JsLifetime, Context, Runtime, Atom, Class};

#[derive(Trace, JsLifetime)]
#[rquickjs::class(exotic)]
pub struct TestClass {
    value: u32,
}

#[rquickjs::exotic]
impl TestClass {
    #[qjs(get)]
    pub fn value(&self, atom: Atom<'_>) -> Option<u32> {
        if atom.to_string().unwrap() == "value" {
            Some(self.value)
        } else {
            None
        }
    }
}

fn main() {
    let rt = Runtime::new().unwrap();
    let ctx = Context::full(&rt).unwrap();

    ctx.with(|ctx| {
        let cls = Class::instance(ctx.clone(), TestClass { value: 42 }).unwrap();
        ctx.globals().set("my_class", cls.clone()).unwrap();
        let value = ctx.eval::<u32, _>(r#"my_class.value"#).unwrap();
        println!("value: {}", value);
        assert_eq!(value, 42);
    })
}