This is unreleased documentation for Yew Next version.
For up-to-date documentation, see the latest version on docs.rs.
yew::html

Trait TargetCast

Source
pub trait TargetCast
where Self: AsRef<Event>,
{ // Provided methods fn target_dyn_into<T>(&self) -> Option<T> where T: AsRef<EventTarget> + JsCast { ... } fn target_unchecked_into<T>(&self) -> T where T: AsRef<EventTarget> + JsCast { ... } }
Expand description

A trait to obtain a generic event target.

The methods in this trait are convenient helpers that use the JsCast trait internally to do the conversion.

Provided Methods§

Source

fn target_dyn_into<T>(&self) -> Option<T>
where T: AsRef<EventTarget> + JsCast,

Performs a dynamic cast (checked at runtime) of this events target into the type T.

This method can return None for two reasons:

  • The event’s target was None
  • The event’s target type did not match T
§Example
use web_sys::HtmlTextAreaElement;
use yew::prelude::*;

fn view(&self, ctx: &Context<Self>) -> Html {
    html! {
        <div
            onchange={ctx.link().batch_callback(|e: Event| {
                if let Some(input) = e.target_dyn_into::<HtmlTextAreaElement>() {
                    Some(Msg::Value(input.value()))
                } else {
                    None
                }
            })}
        >
            <textarea />
            <input type="text" />
        </div>
    }
}

Note: if you can apply the Callback directly onto an element which doesn’t have a child consider using TargetCast::target_unchecked_into<T>

Source

fn target_unchecked_into<T>(&self) -> T
where T: AsRef<EventTarget> + JsCast,

Performs a zero-cost unchecked cast of this events target into the type T.

This method does not check whether the event target is an instance of T. If used incorrectly then this method may cause runtime exceptions in both Rust and JS, this should be used with caution.

A common safe usage of this method is within a Callback that is applied directly to an element that has no children, thus T will be the type of the element the Callback is applied to.

§Example
use web_sys::HtmlInputElement;
use yew::prelude::*;

fn view(&self, ctx: &Context<Self>) -> Html {
    html! {
        <input type="text"
            onchange={ctx.link().callback(|e: Event| {
                // Safe to use as callback is on an `input` element so this event can
                // only come from this input!
                let input: HtmlInputElement = e.target_unchecked_into();
                Msg::Value(input.value())
            })}
        />
    }
}

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§