【问题标题】:Coffeescript member is undefinedCoffeescript 成员未定义
【发布时间】:2014-02-03 17:59:11
【问题描述】:

我收到以下错误:

未捕获的类型错误:无法调用未定义的方法 '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()

我尝试在 connect 内部和发出之前再次应用相同的解决方案(见下文),但没有得到任何输出:

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

谢谢。

【问题讨论】:

标签: coffeescript


【解决方案1】:

您的发射永远不会被触发,因为发射发送数据并因此需要一个数据结构。 请像这样更改您的代码

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

我不确定(嗯,我很确定,但还没有尝试过)你可以通过网络发送一个闭包。

【讨论】:

    猜你喜欢
    • 2012-04-13
    • 1970-01-01
    • 2020-09-18
    • 2021-03-04
    • 2022-01-08
    • 1970-01-01
    • 2013-05-02
    • 2020-09-19
    • 2021-11-26
    相关资源
    最近更新 更多