I’m trying to use a custom object’s method to emit to a socket connection. The object is defined outside of the socket connection, but then instantiated inside of it. Code and error follows.
app.js
...
io.sockets.on('connection', function (socket) {
report = new Report();
socket.on('dataChange', function(newData) {
report.update(newData);
});
});
function Report () {
this.update = function (data) {
socket.emit('updateReport', { data: data });
}
}
Error
Node gives me the following error.
socket.emit(‘updateReport’, { data: data });
^ReferenceError: socket is not defined
You could pass
sockettoReportlike this:That way,
socketis accessible inReport.However, you used
reportas a variable that’s not local to the connection handler. Are you sure you’re not overwritingreportacross connections? It seems you rather want a report per connection. In that case, prependvarto thereportassignment.