#事件监听 #事件 #监听器 #发射器

事件监听原语

构建类似 Node.js 的事件监听器的底层原语

7 个版本 (3 个稳定版)

2.0.1 2021 年 9 月 2 日
2.0.0 2021 年 8 月 30 日
1.0.0 2021 年 6 月 13 日
0.2.2 2020 年 12 月 22 日
0.1.0 2020 年 10 月 24 日

#849 in Rust 模式

Download history 732/week @ 2024-03-14 376/week @ 2024-03-21 342/week @ 2024-03-28 348/week @ 2024-04-04 333/week @ 2024-04-11 223/week @ 2024-04-18 311/week @ 2024-04-25 284/week @ 2024-05-02 376/week @ 2024-05-09 248/week @ 2024-05-16 259/week @ 2024-05-23 459/week @ 2024-05-30 252/week @ 2024-06-06 330/week @ 2024-06-13 172/week @ 2024-06-20 124/week @ 2024-06-27

924 下载/每月
用于 3 库(2 个直接使用)

0BSD 许可证

18KB
424

事件监听原语

Build Status Crates.io Docs License

此库提供构建类似 Node.js 的事件监听器的底层原语。

这 3 个原语是:用于 Fn 事件处理器的容器 Bag,用于 FnOnce 事件处理器的 BagOnce,以及在丢弃时从容器中移除事件处理器的 HandlerId

简单示例

use event_listener_primitives::{Bag, HandlerId};
use std::sync::Arc;

fn main() {
    let bag = Bag::default();

    let handler_id = bag.add(Arc::new(|| {
        println!("Hello");
    }));

    bag.call_simple();
}

接近实际使用示例

use event_listener_primitives::{Bag, BagOnce, HandlerId};
use std::sync::Arc;

#[derive(Default)]
struct Handlers {
    action: Bag<Arc<dyn Fn() + Send + Sync + 'static>>,
    closed: BagOnce<Box<dyn FnOnce() + Send + 'static>>,
}

pub struct Container {
    handlers: Handlers,
}

impl Drop for Container {
    fn drop(&mut self) {
        self.handlers.closed.call_simple();
    }
}

impl Container {
    pub fn new() -> Self {
        let handlers = Handlers::default();

        Self { handlers }
    }

    pub fn do_action(&self) {
        // Do things...

        self.handlers.action.call_simple();
    }

    pub fn do_other_action(&self) {
        // Do things...

        self.handlers.action.call(|callback| {
            callback();
        });
    }

    pub fn on_action<F: Fn() + Send + Sync + 'static>(&self, callback: F) -> HandlerId {
        self.handlers.action.add(Arc::new(callback))
    }

    pub fn on_closed<F: FnOnce() + Send + 'static>(&self, callback: F) -> HandlerId {
        self.handlers.closed.add(Box::new(callback))
    }
}

fn main() {
    let container = Container::new();
    let on_action_handler_id = container.on_action(|| {
        println!("On action");
    });
    container
        .on_closed(|| {
            println!("On container closed");
        })
        .detach();
    // This will trigger "action" callback just fine since its handler ID is not dropped yet
    container.do_action();
    drop(on_action_handler_id);
    // This will not trigger "action" callback since its handler ID was already dropped
    container.do_other_action();
    // This will trigger "closed" callback though since we've detached handler ID
    drop(container);

    println!("Done");
}

输出将如下

On action
On closed
Done

贡献

请随意创建问题和发送拉取请求,它们非常受欢迎!

许可证

零条款 BSD 许可证

https://opensource.org/licenses/0BSD

https://tldrlegal.com/license/bsd-0-clause-license

依赖项

~0.5–0.8MB
~13K SLoC