I'm new to node.js and having a hard time grasping the event listener / emitter dynamic. I'm trying to set up a simple long-polling listener for a typical 'newsfeed' app. I'm able to register and emit events to listeners with the code below. My problem is that each time an event is emitted, it is pushed to the client-side multiple (two or more!) times.
var http = require('http'),
events = require('events'),
url = require('url');
var event_emitter = new events.EventEmitter();
http.createServer(function(req,res) {
var uriParse = url.parse(req.url,true);
var pathname = uriParse.pathname;
console.log(req.url);
if (pathname=="//register") {
var thisRes = res;
event_emitter.addListener('event',function(actionid){
if (thisRes) {
thisRes.writeHead(200, { "Content-Type": "text/plain" });
thisRes.end(actionid);
thisRes = null;
}
});
} else if (pathname=="//emit") {
var actionid = uriParse.query.id;
event_emitter.emit('event',actionid);
console.log('event',actionid);
res.writeHead(200, { "Content-Type": "text/plain" });
res.end('success');
}
}).listen(3000,"127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');
The console log is showing two 'register' requests for every ajax request and I'm not sure from where the ?get queries originate:
//register?=1304280004069
//register?=1304280004068
Client's ajax call (located in html body):
$(document).ready(function() {
function callNode() {
$.ajax({
url: '/node/register',
cache: false,
timeout: 100000 * 1000000,
success: function(data) {
function doSomethingWithData(newaction) {
$('#feed').prepend(newaction);
}
$.get('/news/'+ data+'/', doSomethingWithData);
callNode();
}
});
};
callNode();
});
Finally, the other issue is that the ajax call is not occurring in the background but the page appears to be "loading" until the first node emission (after which it runs silently in the background). Thanks for any suggestions.
I'm assuming you're using jQuery for the client request. It looks like by setting cache to false, jQuery is adding in a unique query string to each request to make sure you get new data.
You may also want to move the doSomethingWithData method out of your AJAX call to make it a bit easier to read.
$(document).ready(function() {
function doSomethingWithData(newaction) {
$('#feed').prepend(newaction);
}
(function callNode() {
$.ajax({
url: '/node/register',
cache: false,
timeout: 100000 * 1000000,
success: function(data) {
$.get('/news/'+ data+'/', doSomethingWithData);
callNode();
}
});
}());
});