Commits

Anonymous committed 1e856f8

Add event:

Comments (0)

Files changed (2)

 }
 
 function drawTree(comments) {
-  for(i in comments) {
-    insertComment(comments[i]);
-  }
+    for(i in comments) {
+        insertComment(comments[i]);
+    }
 }
 
 setTimeout(function() {
-  var source = new EventSource('/events');
-  source.onmessage = function(e) {
-    var d = JSON.parse(e.data);
-    if(d.comments) drawTree(d.comments);
-    if(d.comment) insertComment(d.comment);
-  };
-  source.onopen = function(e) {
-  };
-  source.onerror = function(e) {
-  };
+    var source = new EventSource('/events');
+    source.addEventListener('comments', function(e) {
+        drawTree(JSON.parse(e.data));
+    }, false);
+    source.addEventListener('comment', function(e) {
+        insertComment(JSON.parse(e.data));
+    }, false);
+    source.onopen = function(e) {
+    };
+    source.onerror = function(e) {
+    };
 }, 500);
 
 function defaultForm() {
         db.collection('comments', function(error, comments) {
             comments.find({}, {sort: [['_id', 1]]}, function(error, cursor) {
                 cursor.toArray(function(error, data) {
-                    response.write('id: ' + (new Date()).toLocaleTimeString() + '\n');
-                    response.write('data: ' + JSON.stringify({comments: data}) + '\n\n');
+                    response.write('event: comments\n');
+                    response.write('data: ' + JSON.stringify(data) + '\n\n');
                 });
             });
         });
 
         sseCallback = function(comment) {
-            var id = (new Date()).toLocaleTimeString();
 //            request.session.reload(function(e) {
-                response.write('id: ' + id + '\n');
-                response.write('data: ' + JSON.stringify({comment: comment}) + '\n\n');
+                response.write('event: comment\n');
+                response.write('id: ' + comment['_id'] + '\n');
+                response.write('data: ' + JSON.stringify(comment) + '\n\n');
+                console.log(comment['_id']);
 //                console.log(request.session.user);
 //            });
         }
         console.log('Client connected: ' + request.session.user);
         request.on('close', function() {
             sse.removeListener('comment', sseCallback);
+            response.end();
             console.log('Request close!');
         });
     } else response.send(404);