Event emitter with conditions

问题: I've created an event emitter class. It works properly. Let me tell you how: This is the class: class EventEmitter{ constructor() { this.events = {}; }...

问题:

I've created an event emitter class. It works properly. Let me tell you how:

This is the class:

class EventEmitter{

    constructor() {
        this.events = {};
    }

    on(eventName,callback) {
        if(this.events[eventName]) {
            this.events[eventName].push(callback);
        } else {
            this.events[eventName] = [callback]; 
        }
    }

    trigger(eventName, ...rest) {
        if(this.events[eventName]) {
            this.events[eventName].forEach(cb => {
                cb.apply(null,rest); 
            });
        }
    }
 }

With this class i can listen to certain events. Like so :

 const ee = new EventEmitter();
 ee.on('change', (aa) => {
     console.log(aa);
 });

Then i can trigger it with the trigger method

 ee.trigger('change','Argument');

Now i want to listen to events with certain conditions.

for example :

 ee.on({'change': 'barack the boss'}, (aa) => {
     console.log(aa);
 });

The above bit of code should only execute when trigger looks like this:

 //wont run
 ee.trigger('change','barack is no boss');
//will run
 ee.trigger('change','barack the boss');

I wonder how to do this. I am not asking you to write my code, I would like an example or a step in the right direction.

Thank you in advance.

Whole code:

class EventEmitter{

    constructor() {
        this.events = {};
    }

    on(eventName,callback) {
        if(this.events[eventName]) {
            this.events[eventName].push(callback);
        } else {
            this.events[eventName] = [callback]; 
        }
    }

    trigger(eventName, ...rest) {
        if(this.events[eventName]) {
            this.events[eventName].forEach(cb => {
                cb.apply(null,rest); 
            });
        }
    }
 }

//events has been created and is currently an empty object
 const ee = new EventEmitter();

//even has been created, this event has a function which will be executed when event is triggered
 ee.on({'change': 'barack the boss'}, (aa) => {
     console.log(aa);
 });

 //wont run
 ee.trigger('change','barack is no boss');
//will run
 ee.trigger('change','barack the boss');

回答1:

What I would do is use Object.Keys on the .on() event register. This would allow you to iterate trough the object passed (which at the same time would give you the ability to register multiple events in a single call).

With Object.Keys you can iterate trough the argument object as if it were an array. Then you can register the the value of the key as a condition when triggering the event.

  • 发表于 2019-03-23 14:44
  • 阅读 ( 224 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除