CoffeeScript中的多个回调 [英] Multiple Callbacks in CoffeeScript
问题描述
我正在尝试找出正确的行为以将多个回调字符串在一起.
I am trying to work out the correct behavior to string multiple callbacks together.
class Person
move_head: ->
head.animate({
left: x,
},{
complete: @move_foot,
});
move_foot: ->
foot.animate({
left: x,
},{
complete: @move_arm,
});
move_arm: ->
arm.animate({
left: x,
},{
complete: something_else,
});
现在的问题是,头部动画效果很好,叫脚.脚也可以动画.问题是,做完脚后,它不会使手臂动起来.我不知道可能是什么问题.我猜想这可能与范围界定问题有关.
Now the issue is, head animates fine which calls foot. Foot also animates fine. The problem is that when foot is done, it does not animate the arm. I can't figure out what the problem could be. I have a guess though that it might have to do with a scoping issue.
推荐答案
使用粗箭头=>
将this
绑定到当前上下文:
Use the fat arrow =>
, to bind this
to current context:
move_head: =>
// ...
move_foot: =>
// ...
move_arm: =>
// ...
更新:这是一个简短的解释:
UPDATE: Here's a short explanation:
this
是javascript中最大的陷阱之一.在方法(例如您的move_head
)中,如果您将其称为new Person().move_head()
,则this
是Person的实例.但这不是必须的.例如,如果使用new Person().move_head.call(null)
进行调用,则this
将为null
.
One of the biggest gotchas in javascript is this
. In a method (such as your move_head
), this
is your instance of Person, if you call it as new Person().move_head()
. But it doesn't have to be. For instance, if you call it using new Person().move_head.call(null)
, this
will be null
.
但是最大的陷阱是,当您位于function
中时,就像对jQuery动画调用的complete
回调一样,this
不再绑定到您的对象!它可能绑定到window
,但不是确定的.因此,在您的情况下发生的是,您给jQuery提供了对@move_foot
(或者实际上是this.move_foot
)的引用.该调用似乎有效,因为动画已完成.但是当jQuery调用该函数时,它将不再知道this
应该是您的Person.因此,当您告诉它然后转到@move_arm
时,它将在其他对象(也许是window
)上寻找方法move_arm
.
But the biggest gotcha is that when you are inside a function
, like a complete
callback to a jQuery animate call, this
is no longer bound to your object! It is probably bound to window
, but not for certain. So what happens in your case is that you give jQuery a reference to @move_foot
(or really, this.move_foot
). This call seems to work, in that your animation completes. But when jQuery calls that function, it will no longer know that this
is supposed to be your Person. So when you tell it to then go to @move_arm
, it will look for a method move_arm
on some other object (perhaps window
).
解决此问题的一种常用方法是在进行调用之前保存对this
的引用,例如var self = this
,然后在回调内部引用该绑定变量self
.
A common way to solve this is to save a reference to this
before you make the call, like var self = this
, and then, inside the callback, refer to that bound variable self
instead.
您可以使用此技术,它没有任何问题.像这样:
You could use this technique, there is nothing wrong with it. Something like:
move_head: ->
self = this
head.animate(..., complete: self.move_foot)
但是CS会通过为您提供粗箭头:=>
为您执行此操作(绑定this
).
But CS does this (binding of this
) for you, by giving you the fat arrow: =>
.
粗箭头表示:此方法中引用this
的所有内容均应引用该对象."
The fat arrow says: "Everything inside this method referring to this
, shall refer to this object."
这篇关于CoffeeScript中的多个回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!