0

I get the following error:

Uncaught TypeError: Cannot call method 'push' of undefined

In the next code:

class classDemo

names : ['t1', 't2']

methodM1: () ->
  # This works:
  @names.push 't3'
  console.log @names.toString()

  @socket = io.connect()
  @socket.on 'connect', () ->
    # This raise the error:
    @names.push 't4'
    console.log @names.toString()

Does anyone know how to push into "names" inside the socket.on method? (How to push 't4' correctly?

Thanks

EDIT: The solution proposed by @Sven works for one level of chaining. It seems to fail for two chained calls. Please consider the following example:

  methodM1: () ->
    _this = @
    @socket = io.connect() # connect with no args does auto-discovery
    @socket.on 'connect', () ->
      # This works:
      _this.names.push 'inside connect'
      console.log _this.names.toString()
      @socket.emit 'getModels', (data) ->
        # This does not work:
        _this.names.push 'inside emit'
        console.log _this.names.toString()

I tried to apply the same solution again inside connect and before emit (see below) but I get no output:

      _this2 = _this
      @socket.emit 'getModels', (data) ->
        _this2.names.push "inside emit"
        console.log _this2.names.toString()

Thanks.

Dconversor
  • 73
  • 1
  • 8

1 Answers1

0

your emit is never fired because emit sends data and requieres therefore a datastructure. Please change your code like this

a) use the fat arrow b) emit a data structure

methodM1: ->
    @socket = io.connect()
    #here use the fat arrow it does the '_this = @ automatically'
    @socket.on 'connect', =>
        @names.push 'inside connect'
        console.log _this.names.toString()
        @socket.emit 'getModels', yo: "got your message"

The fat arrow always binds to the outer instance (see When does the "fat arrow" (=>) bind to "this" instance)

I am not sure (well, I am pretty sure but havent tried it) that you can send a closure over the wire.

Community
  • 1
  • 1
robkuz
  • 9,488
  • 5
  • 29
  • 50