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

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();

    // ...
});

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();

    // ...
});

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();

    // ...
});

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();

    // ...
});

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!

Returns the EventTarget.

Returns the event type.

Returns the callback.

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

Formats the value using the given formatter. Read more

Executes the destructor for this type. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

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

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.