Reputation: 2103
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;
Upvotes: 0
Views: 116
Reputation: 106698
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.
Upvotes: 1