简体   繁体   English

Node.js发出给特定的侦听器

[英]Node.js emit to a specific listener

It's possible emit to a specific listener in node.js? 是否可以向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 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. 您将中断/更改模式,或维护许多侦听器列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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