How do I refer to actual 'this' inside CoffeeScript fat-arrow callback?

早过忘川 提交于 2019-12-01 11:26:50

You can achieve your goal in at least three ways. The 1st one would be:

class myClass
    constructor: ->
        element = $ "#id"
        element.click =>
            @myMethod(element.value)
            return
        return

    myMethod: (c) ->
        window.console.log(c)
        return

And the 2nd:

class myClass
    constructor: ->
        element = $ "#id"
        myMethodCallback = (c) => @myMethod(c)
        element.click ->
            myMethodCallback(@value)
            return
        return

    myMethod: (c) ->
        window.console.log(c)
        return

The 3rd one is as showed below. I'm not sure about jQuery API usage though, so better check on appropriate docs page.

class myClass
    constructor: ->
        element = $ "#id"
        element.click (event) =>
            @myMethod(event.target.value)
            return
        return

    myMethod: (c) ->
        window.console.log(c)
        return

I would prefer the 1st way as it seems to be more straightforward. This or the other but you need to decide 'which this' you would like to have in scope of the element.click callback. It's not possible to access two 'thises' at the same time.

By the way. All those return statements seems unnecessary. The shortest working solution would look like:

class myClass
    constructor: ->
        element = $ "#id"
        element.click => @myMethod(element.value)

    myMethod: (c) -> window.console.log(c)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!