Travis
Travis

Reputation: 12379

Can't emit from method defined outside of socket connection

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

Upvotes: 1

Views: 2243

Answers (1)

pimvdb
pimvdb

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

Related Questions