Coffeescript - 'this'在fat arrow回调中总是被'_this'取代 [英] Coffeescript - 'this' is always replaced by '_this' in fat arrow callback

查看:113
本文介绍了Coffeescript - 'this'在fat arrow回调中总是被'_this'取代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可能以某种方式阻止这个关键字转换成 _this 里面fat arrow回调 => )?



例如:

  class someClass 

someMethod: - >
$(document).on'click','.myclass',(e)=>
#做正确的上下文这个,没关系
@anotherMethod()
@oneMoreMethod()

#但这里我需要jQuery``this``指向到元素
$ el = $ this#这被转换成``_this`` :(

可能我错过了一些选项或操作符?



UPDATE
我知道如 = this ,但我认为CS有更优雅的东西。

解决方案

=>



使用 $(e.currentTarget)获得一个 元素的句柄,这与 $(e.target)不一样

没有,CoffeeScript 不能有任何更优雅的方式来处理这个问题,你只能有一个函数的上下文绑定函数不是CoffeeScript的特有的,它们是JavaScript的一个特性,解决方案是为调用代码提供另一种访问元素的方式,jQuery用 e.target e.currentTarget


I'm wondering is possible somehow to prevent this keyword to be transformed into _this inside fat arrow callback (=>)?

For example:

class someClass

  someMethod: ->
    $(document).on 'click', '.myclass', (e) =>
      # doing things with right context this, it's ok
      @anotherMethod()
      @oneMoreMethod()

      # but here I need jQuery ``this`` pointing to element
      $el = $ this # this is transformed into ``_this`` :(

Maybe I missed some option or operator?

UPDATE I know about the trick like self = this, but I thought CS has something more elegant..

解决方案

That's the whole purpose of =>.

Use $(e.currentTarget) to get a handle to the element that would have been this. This is not the same as $(e.target) which you have already rejected.

And no, CoffeeScript can't have anything more elegant way to handle this. You can only have one context for a function. Bound functions aren't unique to CoffeeScript, they're a feature of JavaScript, and the solution is for the calling code to provide another way of accessing the element, which jQuery does with e.target and e.currentTarget.

这篇关于Coffeescript - 'this'在fat arrow回调中总是被'_this'取代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆