从 CoffeeScript 中的点击处理程序中调用另一个函数或方法

Calling another function or method from within a click handler in CoffeeScript

我是 CoffeeScript n00b,我正在努力从我的点击处理程序中调用另一个函数。

第一个警报出现,但第二个警报不出现。

CourseGuide =

    init: ->

      $('.js-size-unit-button').on 'click', (e) ->
        alert 'hello world - test'
        @clickHandler(e)

      clickHandler: (e) ->
        e.preventDefault()
        console.log 'hello world - test 2'
        alert 'hello world - test 2'

module.exports = CourseGuide

这是控制台中的错误:

TypeError: this.clickHandler is not a function

我有基本语法错误吗?

你就快完成了...从这里更改代码:

$('.js-size-unit-button').on 'click', (e) ->

对此:

$('.js-size-unit-button').on 'click', (e) =>

为什么这行得通? "fat arrow" (=>) 告诉 CoffeeScript 编译器确保事件处理程序中 this 的值引用您定义的 class,而不是其他内容。通常,在 Javascript 中,如果您在事件处理程序中使用 this,则 this 指的是触发事件的元素。

这在 Coffescript 文档中有描述in the section entitled "Bound Functions, Generator Functions"

您可能还需要更改 init 方法的声明:

init: ->

至:

init: =>

确保 this 的值在定义事件处理程序时有可参考的东西。