Trait webui::TargetCast
source · [−]pub trait TargetCast: AsRef<Event> {
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
sourcefn target_dyn_into<T>(&self) -> Option<T>where
T: AsRef<EventTarget> + JsCast,
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 yew::prelude::*;
use web_sys::HtmlTextAreaElement;
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>
sourcefn target_unchecked_into<T>(&self) -> Twhere
T: AsRef<EventTarget> + JsCast,
fn target_unchecked_into<T>(&self) -> Twhere
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 yew::prelude::*;
use web_sys::HtmlInputElement;
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())
})}
/>
}
}