CoffeeScript:如何同时使用胖箭头和 this? [英] CoffeeScript: How to use both fat arrow and this?
本文介绍了CoffeeScript:如何同时使用胖箭头和 this?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个咖啡脚本类,它有一些 jquery 事件监听器.我想使用粗箭头 =>
来避免引用类,但我仍然需要引用通常与 this
一起使用的元素.如何同时使用两者?
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 need a reference to the element that would usually be used with this
. How can I use both?
class PostForm
constructor: ->
$('ul.tabs li').on 'click', =>
tab = $(this)
@highlight_tab(tab)
@set_post_type(tab.attr('data-id'))
highlight_tab: (tab)->
tab.addClass 'active'
set_post_type: (id) ->
$('#post_type_id').val(id)
推荐答案
CoffeeScript 将 this
和 @
都链接到外部上下文,因此您无法访问 jQuery 的上下文提供(又名所需的这个").请改用 event.target
:
CoffeeScript links both this
and @
to the outer context, therefore you cannot access the context that jQuery provided (aka the desired "this"). Use event.target
instead:
class PostForm
constructor: ->
$('ul.tabs li').on 'click', (event) =>
tab = $(event.target)
@highlight_tab(tab)
这篇关于CoffeeScript:如何同时使用胖箭头和 this?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文