【问题标题】:Coffeescript objects, jquery callback and variable scope conflicts and confusionCoffeescript 对象、jquery 回调和变量范围冲突和混乱
【发布时间】:2013-04-17 23:09:32
【问题描述】:

试图找出完成这项工作的最佳方法:

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'。如何解决?

【问题讨论】:

    标签: javascript jquery coffeescript


    【解决方案1】:

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

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

    【讨论】:

    • 这是最好的方法吗?谢谢顺便说一句。
    • @Zenph 是的,这是最好的(最易读的)方法。您不能使用this 指向同一上下文中的不同对象。
    • 我了解上下文 ;) 希望 CS 或 jQuery 有一个代理变量来解决此类冲突。
    猜你喜欢
    • 2015-05-26
    • 2021-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    • 2012-01-20
    • 1970-01-01
    • 2012-10-20
    相关资源
    最近更新 更多