Expand description
The Web Components standard creates a browser feature that allows you to create reusable components, called Custom Elements.
While web_sys exposes the browser’s CustomElementRegistry interface, it can be hard to use. Creating a Custom Element requires calling customElements.define() and passing it an ES2015 class that extends HTMLElement, which is not currently possible to do directly from Rust.
This crate provides a CustomElement trait that, when implemented, allows you to encapsulate any Rust structure as a reusable web component without writing any JavaScript. In theory it should be usable with any Rust front-end framework.
impl CustomElement for MyWebComponent {
fn inject_children(&mut self, this: &HtmlElement) {
inject_style(&this, "p { color: green; }");
let node = self.view();
this.append_child(&node).unwrap_throw();
}
fn observed_attributes() -> &'static [&'static str] {
&["name"]
}
fn attribute_changed_callback(
&mut self,
_this: &HtmlElement,
name: String,
_old_value: Option<String>,
new_value: Option<String>,
) {
if name == "name" {
/* do something... */
}
}
fn connected_callback(&mut self, _this: &HtmlElement) {
log("connected");
}
fn disconnected_callback(&mut self, _this: &HtmlElement) {
log("disconnected");
}
fn adopted_callback(&mut self, _this: &HtmlElement) {
log("adopted");
}
}
#[wasm_bindgen]
pub fn define_custom_elements() {
MyWebComponent::define("my-component");
}
Statics§
- Html
Element Constructor Deprecated
Traits§
- Custom
Element - A custom DOM element that can be reused via the Web Components/Custom Elements standard.
Functions§
- inject_
style - Attaches a
<style>
element with the given content to the element, either to its shadow root (if it exists) or to the custom element itself. - inject_
stylesheet - Attaches a
<link rel="stylesheet">
element with the given URL to the custom element, either to its shadow root (if it exists) or to the custom element itself.