Search code examples
htmlnode.jsdynamicemit

How emit event name can be dynamic in Node.js?


I am trying to create dynamic EventEmitter in Node.js. So , how can the event name can be dynamic.

Code :

var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
num = "1";
fs = require('fs');

 server.listen(4000);

       function handler(req,res){
          fs.readFile(__dirname  + '/index.html',
          function(err,data){
           res.writeHead(500);
           res.end(data);
         });
       }

    app.get('/', function(req, res){
           res.sendfile(__dirname + '/index.html');
    });

    io.sockets.on('connection', function(socket){

         socket.on('send message'+num, function(data){

         io.sockets.emit('new message'+num, data);
    }); 
 });

right now in this example i have given value "1" but i want it to dynamic , so how can i get the dynamic value from a html file. So , that emit event name can be dynamic.

Please let me know , suggest me some solution.


Solution

  • There is rarely a valid reason to use a dynamically created message name and it seriously complicates the life of whoever is trying to listen for those messages (they may not know what message name to listen for). Use one message name and then put the number in the data structure that goes with the message.

    sending:

    io.sockets.emit('new-message', {data: data, item: num});
    

    receiving:

    socket.on('new-message', function(msgData){
        if (msgData.item === xx) {
            // handle just a particular message number here
        }
    }