Trait EventListener

Source
pub trait EventListener<T: Event>: Send + Sync {
    // Required method
    fn handle(&self, event: &T) -> Result<(), Box<dyn Error + Send + Sync>>;

    // Provided method
    fn priority(&self) -> Priority { ... }
}
Expand description

Trait for synchronous event listeners

Implement this trait to create reusable event listeners. For simple cases, you can use closures with the dispatcher’s subscribe or on methods instead.

§Example

use mod_events::{Event, EventListener, Priority};

#[derive(Debug, Clone)]
struct UserRegistered {
    user_id: u64,
    email: String,
}

impl Event for UserRegistered {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

struct EmailNotifier;

impl EventListener<UserRegistered> for EmailNotifier {
    fn handle(&self, event: &UserRegistered) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        // Send email logic here
        println!("Sending email to {}", event.email);
        Ok(())
    }
     
    fn priority(&self) -> Priority {
        Priority::High
    }
}

Required Methods§

Source

fn handle(&self, event: &T) -> Result<(), Box<dyn Error + Send + Sync>>

Handle the event

This method is called when the event is dispatched. Return Ok(()) on success or an error on failure.

Provided Methods§

Source

fn priority(&self) -> Priority

Get the priority of this listener

Higher priority listeners are executed first. Default is Priority::Normal.

Implementors§