0

I have a book.js and server.js file. I run node ./server.js and the server begins to run. I open Google Chrome and open developer console, and inpute book.rate(10), and my emit does not happen anywhere. Maybe I am not understanding eventemitters. The error is "Uncaught Reference error: book is not defined"

Server.js

var http = require('http');
var BookClass = require('./book.js');

http.createServer(function (req, res) {
   res.writeHead(200, {'Content-Type': 'text/plain'});
   res.end('Hello World\n');
var book = new BookClass();
book.on('rated', function() {
 console.log('rated '  + book.getPoints());
}); 
}).listen(9000, '127.0.0.1');
console.log('Server running at http://127.0.0.1:9000/');

Book.js

var util = require("util");
var events = require("events");
var Class = function() { };
util.inherits(Class, events.EventEmitter);
Class.prototype.ratePoints = 0;
Class.prototype.rate = function(points) {
   ratePoints = points;
   this.emit('rated');
};
Class.prototype.getPoints = function() {
   return ratePoints;
}
module.exports = Class;
christopher clark
  • 2,026
  • 5
  • 28
  • 47

1 Answers1

1

You get book is not defined because you haven't defined book on the client side, you have only defined it on the server side.

You cannot magically access server-side variables like that from the browser without some sort of extra library/code to provide that kind of functionality.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • This makes sense, but how would the client then tell the server to give a book rating? I would imagine this would need to be inplace to update a database. – christopher clark Jan 31 '16 at 05:11
  • You could use something like [`socket.io`](http://socket.io/docs/) for that. You wouldn't even need the custom EventEmitter in that case, you could just send messages from the client and you execute the corresponding logic/function on the server-side. – mscdex Jan 31 '16 at 05:34
  • So you have to define all variables in both files in nodejs? – Richard Hamilton Jan 31 '16 at 06:26