Coffeescript成员未定义

时间:2014-02-02 15:07:41

标签: coffeescript

我收到以下错误:

  

未捕获的TypeError:无法调用方法' push'未定义的

在下一个代码中:

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()

有没有人知道如何进入"名称"在socket.on方法里面? (如何推动' t4'正确?

由于

编辑:@Sven提出的解决方案适用于一个级别的链接。两个链式呼叫似乎失败了。请考虑以下示例:

  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()

我试图在连接之前和发射之前再次应用相同的解决方案(见下文),但我没有输出:

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

感谢。

1 个答案:

答案 0 :(得分:0)

你的emit永远不会被触发,因为emit会发送数据并因此需要数据结构。 请更改您的代码

a)使用胖箭头 b)发出数据结构

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"

胖箭头总是绑定到外部实例(请参阅When does the "fat arrow" (=>) bind to "this" instance

我不确定(好吧,我很确定但是没有尝试过)你可以通过电线发送一个封闭物。