51 lines
1.3 KiB
Rust
51 lines
1.3 KiB
Rust
use futures::channel::mpsc;
|
|
use futures::stream::Stream;
|
|
use gloo::{console::log, events::EventListener, net::http::Request, utils::document};
|
|
use std::{
|
|
future::Future,
|
|
pin::Pin,
|
|
task::{Context, Poll},
|
|
};
|
|
use wasm_bindgen::prelude::*;
|
|
use web_sys::EventTarget;
|
|
|
|
// From: https://docs.rs/gloo-events/latest/gloo_events/struct.EventListener.html
|
|
|
|
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 }
|
|
}
|
|
}
|
|
|
|
// Multiple clicks.
|
|
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)
|
|
}
|
|
}
|
|
|
|
// Just one click.
|
|
impl Future for OnClick {
|
|
type Output = ();
|
|
|
|
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
|
Pin::new(&mut self.receiver)
|
|
.poll_next(cx)
|
|
.map(Option::unwrap)
|
|
}
|
|
}
|