1

我注意到,如果我尝试像这样编译 Coffeescript 行:

$note.find('a.close').bind 'click', (event) =>
  $(this).parent().remove()

$(this)编译为$(_this),考虑到我使用的是=>. 问题是,我不想->在以后需要在这个范围内使用局部变量时使用。

我必须用反引号转义第二行才能$this正确编译,à la:

`$(this).parent().remove()`

…或者,还有更好的方法?

更新(2012 年 7 月 12 日):

我最终这样做了:

close = -> $note.remove()
$note.find('a.close').bind 'click', (event) ->
  close()
setTimeout close, duration

我知道它this完全避免了使用,但这似乎是一个比使用self = this普通 JS 开发通常需要的相同技巧更清洁的解决方案。

4

3 回答 3

2

要获取您单击的元素,您可以执行以下操作:

close_button = $(event.currentTarget) // equivalent to $(this) here
close_button.parent().remove()

- - - 或者 - - -

that = @
$note.find('a.close').bind 'click', (event) ->
    $(this).parent().remove()
    that.anotherFunc()

但这并不能真正回答您的问题,但它是一个不错的选择。如果可能,我会自己使用第一个解决方案。

于 2012-07-10T15:11:45.977 回答
1

你真的想用->. 唯一会改变的是该函数中( thisor @) 的值。如果您希望能够同时使用this您当前拥有的和this您想要的,您需要以this不同的名称保持当前关闭

现在的代码:

$note.find('a.close').bind 'click', (event) ->
  $(this).parent().remove()

如果您需要this来自外部范围的代码:

that = this
$note.find('a.close').bind 'click', (event) ->
  that.doSomething()
  $(this).parent().remove()
于 2012-07-11T04:14:10.130 回答
0

据我了解,您只需要缓存变量

that = @

context.action (e) ->
  foo(that)
于 2012-07-10T19:57:32.623 回答