You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I wrote this based on this, but did not get how the pub fn on<F>(&mut self, event: T, handler: F) is working, and how it got fired by calling handler(&payload) in the emit can you explain little bit pls. thanks
use std::collections::HashMap;use std::cmp::Eq;use std::hash::Hash;#[derive(Debug,Copy,Clone,Hash,Eq,PartialEq)]enumGreetEvent{SayHello,SayBye,}typeHandlerPtr<T> = Box<dynFn(&T)>;// Vec<Arc<dyn EventListener>>; //pubstructEventEmitter<T:Hash + Eq,U>{handlers:HashMap<T,Vec<HandlerPtr<U>>>,}impl<T:Hash + Eq,U>EventEmitter<T,U>{/// Creates a new instance of `EventEmitter`.pubfnnew() -> Self{Self{handlers:HashMap::new(),}}/// Registers function `handler` as a listener for `event`. There may be/// multiple listeners for a single event.pubfnon<F>(&mutself,event:T,handler:F)whereF:Fn(&U) + 'static,{let event_handlers =
self.handlers.entry(event).or_insert_with(|| vec![]);
event_handlers.push(Box::new(handler));}/// Invokes all listeners of `event`, passing a reference to `payload` as an/// argument to each of them.pubfnemit(&self,event:T,payload:U){ifletSome(handlers) = self.handlers.get(&event){for handler in handlers {handler(&payload);}}}}fnmain(){letmut emitter = EventEmitter::new();
emitter.on(GreetEvent::SayHello, |name| {println!("Hello, {}!", name);});
emitter.on(GreetEvent::SayHello, |name| {println!("Someone said hello to {}.", name);});
emitter.on(GreetEvent::SayBye, |name| {println!("Bye, {}, hope to see you again!", name);});
emitter.emit(GreetEvent::SayHello,"Alex");
emitter.emit(GreetEvent::SayBye,"Alex");}
The text was updated successfully, but these errors were encountered:
I wrote this based on this, but did not get how the
pub fn on<F>(&mut self, event: T, handler: F)
is working, and how it got fired by callinghandler(&payload)
in theemit
can you explain little bit pls. thanksThe text was updated successfully, but these errors were encountered: