Rust emit
Ninguém assumiu esta issue ainda.
Avaliação
- Dificuldade
- 1/5
- Tempo estimado
- Menos de uma hora
- Facilidade para iniciantes
- 15/100
- Tipo de issue
- Documentação
- Clareza
- Precisa de esclarecimento
- Status de atividade
- Estagnada
- Stack de tecnologia
- rust
- Domínio
- documentation
Direção de pesquisa
Comece pelo exemplo do Rust Playground e pela implementação em Rust de EventEmitter vinculada na issue; em seguida, leia os métodos mostrados EventEmitter::on e emit. Explique como o genérico F, Box<dyn Fn(&U)> e a chamada handler(&payload) se relacionam, usando os exemplos de main como verificação de conclusão.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
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)]
enum GreetEvent {
SayHello,
SayBye,
}
type HandlerPtr<T> = Box<dyn Fn(&T)>; // Vec<Arc<dyn EventListener>>; //
pub struct EventEmitter<T: Hash + Eq, U> {
handlers: HashMap<T, Vec<HandlerPtr<U>>>,
}
impl<T: Hash + Eq, U> EventEmitter<T, U> {
/// Creates a new instance of `EventEmitter`.
pub fn new() -> Self {
Self {
handlers: HashMap::new(),
}
}
/// Registers function `handler` as a listener for `event`. There may be
/// multiple listeners for a single event.
pub fn on<F>(&mut self, event: T, handler: F)
where
F: 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.
pub fn emit(&self, event: T, payload: U) {
if let Some(handlers) = self.handlers.get(&event) {
for handler in handlers {
handler(&payload);
}
}
}
}
fn main() {
let mut 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");
}
- Linguagem predominante
- JavaScript
- Estrelas
- 23
- Forks
- 25
- Métricas de merge de PRs
- Nenhum PR com merge em 30d
Guia de contribuição
Nenhum guia de contribuição indexado para este repositório
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de HowProgrammingWorks/EventEmitter
-
Тесты для EventEmitter Aberta
HowProgrammingWorks/EventEmitter#14 · 1 responsável ·
-
AsyncEmitter Aberta
HowProgrammingWorks/EventEmitter#12 · 1 responsável ·
Todas as issues de HowProgrammingWorks/EventEmitter
Issues semelhantes
-
bug
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 76/100
avniproject/avni-client#2135 ·
-
enhancement
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 70/100
babalae/bettergi-scripts-list#3674 ·
-
A-Release-Notes C-Editing D-Modest S-Ready-For-Implementation
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 72/100
bevyengine/bevy-website#2595 ·
-
ecosystem wording
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 90/100
matrix-org/matrix.org#3649 ·
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 88/100
vadimdemedes/ink#1029 ·