[英]Fat arrow repetition?
When I'm writing coffee script I tend to do this an awful lot (pseudo code): 当我写咖啡脚本时,我倾向于这么做(伪代码):
$link.click (e) =>
this._clicked(e)
Is there really not some way to bind transparently in CoffeeScript? 是否真的没有办法在CoffeeScript中透明地绑定? I'd like to be able to do:
我希望能够做到:
$link.click =this._clicked
or something, which would bind my this._clicked method, directly to the event, keeping its this pointer 或者什么,将我的this._clicked方法直接绑定到事件,保持它的指针
any ideas? 有任何想法吗?
update 更新
_clicked would be defined as: _clicked将被定义为:
_clicked: (e) ->
# some code
Nothing special with coffeescript. 没有什么特别的coffeescript。 Just do
做就是了
$link.click @_clicked
And then define _clicked
as 然后将
_clicked
定义为
_clicked: (e) =>
# some code
It'll pass this._clicked
as the handler for the click event of link
. 它将传递
this._clicked
作为link
的click事件的处理程序。
You can pass any function as callbacks like this. 你可以传递任何函数作为这样的回调。 The keypoint is to not execute the function (there are no () in
@_clicked
). 关键点是不执行该函数(
@_clicked
中没有())。 A function in JS is a normal variable, which can be passed around as parameters to other functions. JS中的函数是一个普通变量,可以作为参数传递给其他函数。
With 同
$link.click ->
youre just passing a function to .click
directly without storing it into a variable. 你只需将函数直接传递给
.click
而不将其存储到变量中。
To keep the this
you either define @_clicked
with a fat arrow or you use JavaScripts bind
function which returns a function where this
is bound to a certain value. 要保持这
this
您可以使用胖箭头定义@_clicked
,也可以使用JavaScripts bind
函数 ,该函数返回一个函数, this
函数绑定到某个值。
CoffeeScript is not adding any extra functionality to JavaScript. CoffeeScript没有为JavaScript添加任何额外的功能。 The Fat arrow just does a bind similar to the
bind
function from the link (if its used in a method definition of a class) or just does the var _this = this
trick when a function is defined inside a function. 胖箭头只是一个绑定类似于链接中的
bind
函数(如果它在类的方法定义中使用),或者只是在函数内定义函数时执行var _this = this
技巧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.