Reputation: 12379
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.
...
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 });
}
}
Node gives me the following error.
socket.emit('updateReport', { data: data });
^ReferenceError: socket is not defined
Upvotes: 1
Views: 2243
Reputation: 154828
You could pass socket
to Report
like this:
io.sockets.on('connection', function (socket) {
report = new Report(socket);
socket.on('dataChange', function(newData) {
report.update(newData);
});
});
function Report (socket) {
this.update = function (data) {
socket.emit('updateReport', { data: data });
}
}
That way, socket
is accessible in Report
.
However, you used report
as a variable that's not local to the connection handler. Are you sure you're not overwriting report
across connections? It seems you rather want a report per connection. In that case, prepend var
to the report
assignment.
Upvotes: 5