DAILY DOCDAILY DOC
Rust
Node
Notes
Ubuntu
Leetcode
  • it-tools
  • excalidraw
  • linux-command
Rust
Node
Notes
Ubuntu
Leetcode
  • it-tools
  • excalidraw
  • linux-command
  • rust

    • Rust
    • add
    • 属性(attributes)
    • cargo issue
    • cli
    • build.rs
    • Enums
    • eventEmitter(rust)
    • 格式化输出 std::fmt
    • rust iterator
    • rust 学习计划
    • 生命周期(lifetime)
    • Linked List
    • log
    • macros
    • mem::size_of
    • niche optimization
    • Rust 所有权
    • 模式匹配(pattern matching)
    • module system
    • result & option
    • .rust-analyzer.json
    • rust startup
    • rust-test
    • 可见性(visibility)
    • cargo
    • toml

eventEmitter(rust)

on emit 简易版本

details
use std::{
    collections::HashMap,
    sync::{Arc, Mutex},
};

type EventHandle<T> = Box<dyn Fn(T) + Send + Sync>;
pub struct EventEmitter<T> {
    listeners: Arc<Mutex<HashMap<String, Vec<EventHandle<T>>>>>,
}

impl<T> EventEmitter<T> {
    pub fn new() -> Self {
        Self {
            listeners: Arc::new(Mutex::new(HashMap::new())),
        }
    }
    pub fn on<F>(&mut self, event: &str, handler: F)
    where
        F: Fn(T) + Send + Sync + 'static,
    {
        let mut listeners = self.listeners.lock().unwrap();
        listeners
            .entry(event.to_string())
            .or_default()
            .push(Box::new(handler))
    }

    pub fn emit(&self, event: &str, data: T)
    where
        T: Clone,
    {
        let listeners = self.listeners.lock().unwrap();
        if let Some(handlers) = listeners.get(event) {
            for cb in handlers {
                cb(data.clone())
            }
        }
    }

    // 注册一个只执行一次的事件处理函数
    pub fn once<F>(&mut self, event: &str, mut handler: F) {
        unimplemented!("Need using id to identify");
    }
}
Last Updated:
Contributors: rosendo
Prev
Enums
Next
格式化输出 std::fmt