pub struct EventListener { /* private fields */ }
Expand description

RAII type which is used to manage DOM event listeners.

When the EventListener is dropped, it will automatically deregister the event listener and clean up the closure’s memory.

Normally the EventListener is stored inside of another struct, like this:

use std::pin::Pin;
use std::task::{Context, Poll};
use futures::stream::Stream;
use futures::channel::mpsc;
use web_sys::EventTarget;

pub struct OnClick {
    receiver: mpsc::UnboundedReceiver<()>,
    // Automatically removed from the DOM on drop!
    listener: EventListener,
}

impl OnClick {
    pub fn new(target: &EventTarget) -> Self {
        let (sender, receiver) = mpsc::unbounded();

        // Attach an event listener
        let listener = EventListener::new(&target, "click", move |_event| {
            sender.unbounded_send(()).unwrap_throw();
        });

        Self {
            receiver,
            listener,
        }
    }
}

impl Stream for OnClick {
    type Item = ();

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
        Pin::new(&mut self.receiver).poll_next(cx)
    }
}

Implementations§

source§

impl EventListener

source

pub fn new<S, F>(target: &EventTarget, event_type: S, callback: F) -> Selfwhere S: Into<Cow<'static, str>>, F: FnMut(&Event) + 'static,

Registers an event listener on an EventTarget.

For specifying options, there is a corresponding EventListener::new_with_options method.

If you only need the event to fire once, you can use EventListener::once instead, which accepts an FnOnce closure.

Event type

The event type can be either a &'static str like "click", or it can be a dynamically constructed String.

All event types are supported. Here is a partial list of the available event types.

Passive

For performance reasons, it is not possible to use event.prevent_default().

If you need to use prevent_default, you must use EventListener::new_with_options, like this:

let options = EventListenerOptions::enable_prevent_default();

EventListener::new_with_options(target, event_type, options, callback)
Capture

By default, event listeners are run in the bubble phase, not the capture phase. The official specification has a good explanation of capturing vs bubbling.

If you want it to run in the capture phase, you must use EventListener::new_with_options, like this:

// This runs the event listener in the capture phase, rather than the bubble phase
let options = EventListenerOptions::run_in_capture_phase();

EventListener::new_with_options(target, event_type, options, callback)
Examples

Registers a "click" event and downcasts it to the correct Event subtype (which is MouseEvent):

let listener = EventListener::new(&target, "click", move |event| {
    let event = event.dyn_ref::<web_sys::MouseEvent>().unwrap_throw();

    // ...
});
source

pub fn once<S, F>(target: &EventTarget, event_type: S, callback: F) -> Selfwhere S: Into<Cow<'static, str>>, F: FnOnce(&Event) + 'static,

This is exactly the same as EventListener::new, except the event will only fire once, and it accepts FnOnce instead of FnMut.

For specifying options, there is a corresponding EventListener::once_with_options method.

Examples

Registers a "load" event and casts it to the correct type (which is ProgressEvent):

let listener = EventListener::once(&target, "load", move |event| {
    let event = event.dyn_ref::<web_sys::ProgressEvent>().unwrap_throw();

    // ...
});
source

pub fn new_with_options<S, F>( target: &EventTarget, event_type: S, options: EventListenerOptions, callback: F ) -> Selfwhere S: Into<Cow<'static, str>>, F: FnMut(&Event) + 'static,

Registers an event listener on an EventTarget.

It is recommended to use EventListener::new instead, because it has better performance, and it is more convenient.

If you only need the event to fire once, you can use EventListener::once_with_options instead, which accepts an FnOnce closure.

Event type

The event type can be either a &'static str like "click", or it can be a dynamically constructed String.

All event types are supported. Here is a partial list of the available event types.

Options

See the documentation for EventListenerOptions for more details.

Examples

Registers a "touchstart" event and uses event.prevent_default():

let options = EventListenerOptions::enable_prevent_default();

let listener = EventListener::new_with_options(&target, "touchstart", options, move |event| {
    event.prevent_default();

    // ...
});

Registers a "click" event in the capturing phase and uses event.stop_propagation() to stop the event from bubbling:

let options = EventListenerOptions::run_in_capture_phase();

let listener = EventListener::new_with_options(&target, "click", options, move |event| {
    // Stop the event from bubbling
    event.stop_propagation();

    // ...
});
source

pub fn once_with_options<S, F>( target: &EventTarget, event_type: S, options: EventListenerOptions, callback: F ) -> Selfwhere S: Into<Cow<'static, str>>, F: FnOnce(&Event) + 'static,

This is exactly the same as EventListener::new_with_options, except the event will only fire once, and it accepts FnOnce instead of FnMut.

It is recommended to use EventListener::once instead, because it has better performance, and it is more convenient.

Examples

Registers a "load" event and uses event.prevent_default():

let options = EventListenerOptions::enable_prevent_default();

let listener = EventListener::once_with_options(&target, "load", options, move |event| {
    event.prevent_default();

    // ...
});

Registers a "click" event in the capturing phase and uses event.stop_propagation() to stop the event from bubbling:

let options = EventListenerOptions::run_in_capture_phase();

let listener = EventListener::once_with_options(&target, "click", options, move |event| {
    // Stop the event from bubbling
    event.stop_propagation();

    // ...
});
source

pub fn forget(self)

Keeps the EventListener alive forever, so it will never be dropped.

This should only be used when you want the EventListener to last forever, otherwise it will leak memory!

source

pub fn target(&self) -> &EventTarget

Returns the EventTarget.

source

pub fn event_type(&self) -> &str

Returns the event type.

source

pub fn callback(&self) -> &Closure<dyn FnMut(&Event)>

Returns the callback.

source

pub fn phase(&self) -> EventListenerPhase

Returns whether the event listener is run during the capture or bubble phase.

The official specification has a good explanation of capturing vs bubbling.

Trait Implementations§

source§

impl Debug for EventListener

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Drop for EventListener

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.