简体   繁体   中英

Node.js emit to a specific listener

It's possible emit to a specific listener in node.js?

A example:

emitter.js

var EventEmitter = require('events').EventEmitter;

module.exports = function() {

    var controller = new EventEmitter();

    return {

        set: function(opts) {
            setTimeout(function() {
                controller.emit('ok', opts);
            }, 10);

            return controller;
        },

        get: function(opts) {
            setTimeout(function() {
                controller.emit('ok', opts);
            }, 10);

            return controller;
        }

    };
};

app.js

var express = require('express'),
    app = express(),
    server = require('http').createServer(app);

server.listen(8080);

var testEmitter = require('./emitter')();

testEmitter.set('set').on('ok', function(resp) {
    console.log('set', resp);
});

testEmitter.get('get').on('ok', function(resp) {
    console.log('get', resp);
});

/*result*/

//set set
//get set
//set get
//get get

My idea is instead to emit for all listeners, I want to emit only for a specific listener.

In other words, instead of having a result of

// set set
// get set
// set get
// get get

I want to have this

// set set
// get get

After spent some time to understand how the events work, I do not know how I can do this.

Any idea?

You are using the standard listener design pattern, whose one of advantages is not to (have to) know listeners...

For you problem, you need to discriminate your listeners in any ways.

You will either break/change the pattern, or maintain many listener lists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM