Reputation: 2017
I want to do something where I can set up a route to a link like /visit
using app.get('/visit', function(req, res){})
etc. And inside that, I want to emit a message like socket.emit("event", "a message")
and then inside my io.on("connection")
function, be able to listen for event
and return the message. All the examples that I've seen seem to have an example of how to do this when an html page is visited... but how can I do it with just general routes that display something like res.json()
?
Upvotes: 0
Views: 596
Reputation: 1332
If you are trying to emit and listen for events within the same file, you should be using the built in event listeners for node, not the specialized ones for socket.io (https://nodejs.org/api/events.html):
var EventEmitter = require('events').EventEmitter;
var eventExample = new EventEmitter;
//You can create event listeners:
eventExample.on('anEvent', function(someData){
//Do something with someData
});
//To trigger an event listener you must emit:
eventExample.emit('anEvent', someData);
Upvotes: 1