Emitter RS
Resurrecting the
event-emitter-rscrate from the ashes.
A simple EventEmitter implementation.
Allows you to subscribe to events with callbacks and also fire those events. Events are in the form of (strings, value) and callbacks are in the form of closures that take in a value parameter.
Getting Started
use EventEmitter;
let mut event_emitter = new;
// This will print <"Hello world!"> whenever the <"Say Hello"> event is emitted
event_emitter.on;
event_emitter.emit;
// >> "Hello world!"
Basic Usage
We can emit and listen to values of any type so long as they implement the serde Serialize and Deserialize traits. A single EventEmitter instance can have listeners to values of multiple types.
use EventEmitter;
use ;
let mut event_emitter = new;
event_emitter.on;
event_emitter.emit;
event_emitter.emit;
// >> "8.0"
// >> "7.0"
// Using a more advanced value type such as a struct by implementing the serde traits
event_emitter.on;
event_emitter.emit;
// >> "Month: January - Day: Tuesday"
Removing listeners is also easy
use EventEmitter;
let mut event_emitter = new;
let listener_id = event_emitter.on;
match event_emitter.remove_listener
Creating a Global EventEmitter
It's likely that you'll want to have a single EventEmitter instance that can be shared accross files;
After all, one of the main points of using an EventEmitter is to avoid passing down a value through several nested functions/types and having a global subscription service.
// global_event_emitter.rs
use Mutex;
use EventEmitter;
// Use lazy_static! because the size of EventEmitter is not known at compile time
lazy_static!
Then we can import this instance into multiple files.
// main.rs
extern crate lazy_static;
use EVENT_EMITTER;
And in another file we can now listen to the <"Hello"> event in main.rs by adding a listener to the global event emitter.
// some_random_file.rs
use EVENT_EMITTER;
License: MIT OR Apache-2.0