0

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?

1 Answer 1

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.