crmpicco
crmpicco

Reputation: 17181

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

I am a CoffeeScript n00b, and I am struggling with calling another function from within my click handler.

The first alert appears, but the second does not.

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

This is the error in the console:

TypeError: this.clickHandler is not a function

Do I have a basic syntax error?

Upvotes: 1

Views: 608

Answers (1)

Kryten
Kryten

Reputation: 15760

You're almost there... Change the code from this:

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

to this:

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

Why does this work? the "fat arrow" (=>) tells the CoffeeScript compiler to ensure that the value of this in the event handler refers to the class you've defined, instead of something else. Usually, in Javascript, if you use this in an event handler, this refers to the element on which the event was triggered.

This is described in the section entitled "Bound Functions, Generator Functions" in the Coffescript documentation.

You may also need to change the declaration of the init method from:

init: ->

to:

init: =>

to ensure that the value of this has something to refer to when the event handler is defined.

Upvotes: 2

Related Questions