简体   繁体   English

调用在回调中定义的函数

[英]Calling a function defined inside a callback

I am having a difficulty understanding Javascript-style function definitions. 我在理解Javascript样式的函数定义时遇到困难。

I have a Websocket server: 我有一个Websocket服务器:

var WebSocketServer = require('ws').Server,
wss = new WebSocketServer();

wss.on('connection', function (ws) {
  ws.on('message', function (message) {
    console.log('received: %s from client', message);
  })
  ws.send('hello client');
})

And I want to send a message to the connected clients when another function importantEvent() is called. 我想在调用另一个函数importantEvent()时向连接的客户端发送消息。

function importantEvent(message) {
  //send message to the connected client
  ws.send('hello client');
}

What is the good way of calling ws.send() inside importantEvent() ? 什么是调用的好方法ws.send()importantEvent()

I use EventEmitter to similar things to avoid a strong module strength. 我将EventEmitter用于类似的事情,以避免强大的模块强度。

// eventManager.js
const EventEmitter = require('events');
class EventManager extends EventEmitter {}
const eventManager = new EventManager();

module.exports = eventManager;

// websocket.js
var eventManager = require('eventManager');
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer();

wss.on('connection', function (ws) {
...
})

function broadcast(data, filter) {
    wss.clients.forEach( ... // depends on library using to web-socket
}

eventManager.on('my-event', function (arg1, arg2) {
    broadcast({arg1, arg2})
});

// in any other files
var eventManager = require('eventManager');

eventManager.emit('my-event', 'hello', 'world');

It's a matter of what clients you want to reach. 这取决于您想吸引哪些客户。 In wss.on('connection'... event, the ws received by the function is the client that is connecting to the server in this event. wss.on('connection'...事件中,函数接收的ws是在此事件中连接到服务器的客户端。

As you want send a message to all the clients connected, you need to use the broadcast method 如果要向所有连接的客户端发送消息,则需要使用广播方法

var WebSocketServer = require('ws').Server,
wss = new WebSocketServer();

function importantEvent(message) {
    // Broadcast to all.
    wss.broadcast = function broadcast(data) {
    wss.clients.forEach(function each(client) {
      if (client.readyState === WebSocket.OPEN) {
        client.send('hello client');
      }
    });
  };
}

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

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