CoffeeScript: How to use both fat arrow and this?

后端 未结 4 1276
既然无缘
既然无缘 2020-12-25 11:55

I have a coffeescript class that has some jquery event listeners. I would like to use the fat arrow => to avoid having to reference the class, but I still ne

4条回答
  •  情深已故
    2020-12-25 12:58

    You may want to access variables set in the constructor from your functions. This would be how you do it (the key is calling the function via self while first extracting this with a thin arrow):

    class PostForm
        constructor: ->
            self = this
    
            @some_contrived_variable = true
    
            $('ul.tabs li').on 'click', ->
                tab = $(this)
                self.highlight_tab(tab)
                self.set_post_type(tab.attr('data-id'))
    
        highlight_tab: (tab) ->
            # Because of the fat arrow here you can now access @ again
            if @some_contrived_variable
                tab.addClass 'active'
    
        set_post_type: (id) ->
            $('#post_type_id').val(id)
    

    BTW: This is a great explanation of when to use the fat and thin arrow.

    Summary:

    1. Do you use this (@) in the function?
    2. Do you want to execute the function later, possibly from a different scope?

提交回复
热议问题