Event listener primitives

Build Status Crates.io Docs License

This crate provides a low-level primitive for building Node.js-like event listeners.

The 2 primitives are Bag that is a container for event handlers and HandlerId that will remove event handler from the bag on drop.

Trivial example: ```rust use eventlistenerprimitives::{Bag, HandlerId};

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

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

bag.call_simple();

} ```

Close to real-world usage example: ```rust use eventlistenerprimitives::{Bag, HandlerId}; use std::sync::Arc;

[derive(Default)]

struct Handlers { bar: Bag<'static, dyn Fn() + Send>, closed: Bag<'static, dyn FnOnce() + Send>, }

struct Inner { handlers: Arc, }

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

[derive(Clone)]

pub struct Foo { inner: Arc, }

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

    let inner = Arc::new(Inner { handlers });

    Self { inner }
}

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

    self.inner.handlers.bar.call_simple();
}

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

    self.inner.handlers.bar.call(|callback| {
        callback();
    });
}

pub fn on_bar<F: Fn() + Send + 'static>(&self, callback: F) -> HandlerId {
    self.inner.handlers.bar.add(Box::new(callback))
}

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

}

fn main() { let foo = Foo::new(); let onbarhandlerid = foo.onbar(|| { println!("On bar"); }); foo .onclosed(|| { println!("On closed"); }) .detach(); // This will trigger "bar" callback just fine since its handler ID is not dropped yet foo.dobar(); drop(onbarhandlerid); // This will not trigger "bar" callback since its handler ID was already dropped foo.doother_bar(); // This will trigger "closed" callback though since we've detached handler ID drop(foo);

println!("Done");

} ```

The output will be: text On bar On closed Done

Contribution

Feel free to create issues and send pull requests, they are highly appreciated!

License

Zero-Clause BSD

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

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