【问题标题】:Calling method from click binding从点击绑定调用方法
【发布时间】:2014-11-21 17:13:37
【问题描述】:

我有这个小提琴:http://jsfiddle.net/jj258ykp/2/

对于 BTN2 和 BTN3,我在单击时看到警报,我在 BTN1 上看不到警报,我想看到它。

这是咖啡脚本:

class A

    method: -> 
        alert "method"

    method2: -> 
        alert "method2"

    @method3: -> 
        alert "method3"

    setup: -> 
        $('button#btn').click( (event) -> 
          @method()
        )
        $('button#btn3').click( (event) -> 
          A.method3()
        )



$ ->
    a = new A
    a.setup()

    $('button#btn2').click( (event) -> 
          a.method2()
        )

这是我的 HTML:

<button id = "btn">BTN1</button>
<button id = "btn2">BTN2</button>
<button id = "btn3">BTN3</button>

【问题讨论】:

    标签: javascript jquery events coffeescript


    【解决方案1】:

    您正在尝试引用 this.method()(coffeescript 中的 @ 表示 this)。

    由于调用在点击处理程序的范围内,this.method 将不存在。您需要通过实例化A 或使method 成为method3 之类的成员变量来访问它:

      setup: -> 
        $('button#btn').click( (event) -> 
          new A().method();
        )
    

    或者:

    A
      @method: -> 
        alert "method"
    
      setup: -> 
        $('button#btn').click( (event) -> 
          A.method();
        )
    

    【讨论】:

    • 他们也可以绑定:$('button#btn').bind 'click', (event) =&gt;
    • 谢谢,但我不明白与 BTN2 有什么区别,其中包含对 a 的引用
    • @dongiulio:@ (AKA this) 的值取决于函数的调用方式,而不是(通常)它的定义方式或声明位置。当 jQuery 调用回调时,jQuery 会将 @ 设置为相关的 DOM 元素,因此 @ 将是单击处理程序中的 #btn 元素,而不是 A 实例。
    猜你喜欢
    • 2015-10-31
    • 1970-01-01
    • 2014-10-21
    • 2013-06-21
    • 2018-08-31
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 2013-02-18
    相关资源
    最近更新 更多