1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.