Coffeescript成员未定义
我得到以下错误: 未捕获的TypeError:无法调用未定义的方法“push” 在下一个代码中:Coffeescript成员未定义,coffeescript,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
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方法中插入“names”吗?(如何正确推动“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内部和emit之前再次应用相同的解决方案(见下文),但没有得到任何输出:
_this2 = _this
@socket.emit 'getModels', (data) ->
_this2.names.push "inside emit"
console.log _this2.names.toString()
谢谢。您的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"
胖箭头始终绑定到外部实例(请参见)
我不确定(嗯,我很确定,但还没有试过)你是否可以通过电线发送一个闭包 看看