DelSkayn / rquickjs

High level bindings to the quickjs javascript engine
MIT License
431 stars 58 forks source link

How do I add singleton static classes to global? #321

Open stevefan1999-personal opened 1 month ago

stevefan1999-personal commented 1 month ago

I'm implementing some API from Web standard, and I often use this:

#[rquickjs::module]
pub mod text {
    use rquickjs::{module::Exports, Ctx};

    pub use super::{TextDecoder, TextEncoder};

    #[qjs(evaluate)]
    pub fn evaluate<'js>(ctx: &Ctx<'js>, exports: &mut Exports<'js>) -> rquickjs::Result<()> {
        for (k, v) in exports.iter() {
            ctx.globals().set(k.to_str()?, v)?;
        }

        Ok(())
    }
}

I tried to do this:

#[rquickjs::module]
pub mod text {
    use rquickjs::{class::JsClass, module::Exports, Ctx};

    pub use super::{TextDecoder, TextEncoder};

    #[qjs(evaluate)]
    pub fn evaluate<'js>(ctx: &Ctx<'js>, _exports: &Exports<'js>) -> rquickjs::Result<()> {
        ctx.globals()
            .set("TextDecoder", TextDecoder::prototype(ctx))?;
        ctx.globals()
            .set("TextEncoder", TextEncoder::prototype(ctx))?;

        Ok(())
    }
}

But it doesn't work. What is the proper way to add https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder and https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder into the global context during initialization?

DelSkayn commented 3 weeks ago

If you want to add a new API you must manually add it to the global object after creating a context. Rquickjs currently has no support doing this for you.