Coffeescript对象、jquery回调和变量作用域的冲突和混淆

Coffeescript objects, jquery callback and variable scope conflicts and confusion

本文关键字:冲突 作用域 变量 jquery 回调 Coffeescript 对象      更新时间:2023-09-26

试图找到最好的方法来完成这项工作:

class Person
  constructor: (@el) ->
    @el = $(el)
    this.bind()
  bind: ->
    @el.find('.something').on 'click', ->
      $(this).hide()       # conflict!
      this.do_something()  # conflict!
  do_something: ->
    alert 'done!'

我知道我可以使用哈希火箭(=>),然后从我的回调中访问this.do_something,但这与callback 'this'冲突,所以jquery试图选择对象,而不是element '.something'。如何解决这个问题?

你不能让this引用不同的对象。使用不同的标识符,将实例的this引用存储在辅助变量中:

  bind: ->
    person = this
    @el.find('.something').on 'click', ->
      $(this).hide()
      person.do_something()