Code Monkey home page Code Monkey logo

eventemitter's Introduction

EventEmitter Examples

Таймеры, таймауты, EventEmitter

eventemitter's People

Contributors

aqrln avatar dzyubspirit avatar marylynjuana avatar olecsiuyae avatar pavlyukvadim avatar seregy avatar tshemsedinov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

eventemitter's Issues

Rust emit

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");
}

Доработка примера с EventEmitter

Для примера
https://github.com/HowProgrammingWorks/EventEmitter/blob/master/JavaScript/1-simple.js

let ee = new EventEmitter();
let fn = function(data) {
  console.dir(data);
};
ee.on('smth', fn);

Для @YARTI:

ee.get('smth'); // получить массив обработчиков по имени события
ee.remove('smth', fn); // удалить обработчик события
ee.shuffle('smth'); // перемешать обработчики

Для @GeorgeUA

ee.has('smth'); // есть ли хоть один обработчик
ee.clear('smth'); // очистить все обработчики
ee.onBefore('smth', fn); // вставить событие до уже имеющихся

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.