Module closure

Support for closures in wasm-bindgen

This module defines the ScopedClosure type which is used to pass Rust closures to JavaScript. All closures are unwind safe by default: panics are caught and converted to JavaScript exceptions when built with panic=unwind.

Immutable by Default

The closure API defaults to immutable (Fn) closures because they are more likely to satisfy UnwindSafe automatically:

This means:

Immutable closures can be upcasted to mutable closures using upcast_ref.

Type Aliases

Unwind Safety

For immediate/synchronous callbacks, use &dyn FnMut / &dyn Fn, when you are absolutely sure the code will support unwind safety.

For ScopedClosure, the default constructors (borrow, borrow_mut, own) catch panics, while the _aborting variants (borrow_aborting, borrow_mut_aborting, etc.) do not.

Ownership Model

ScopedClosure follows the same ownership model as other wasm-bindgen types: the JavaScript reference remains valid until the Rust value is dropped. When dropped, the closure is invalidated and any subsequent calls from JavaScript will throw an exception.

For borrowed closures created with borrow/borrow_mut, Rust's borrow checker ensures the ScopedClosure cannot outlive the closure's captured data.

See the ScopedClosure type documentation for detailed examples.

Structs

Type Aliases