Alexis
Alexis

Reputation: 25163

Premature code execution with CoffeeScript

I have an animation that is mostly working with jQuery and CoffeeScript.

I have come a problem though that I can't quite figure out.

class Cow
  move_head: (x, y)=>
    stander.animate({
left: 10,
  },{
    complete: @move_feet(x, y)
  });

  move_feet: (x, y)=>
    stander.animate({
left: 10,
  },{
    complete: @mover_in_test
  });

The problem is with complete: @move_feet(x, y). When there are no arguments, complete: @move_feet the code works fine and @move_feet is called when the move_head animation is completed. However, with complete: @move_feet(x, y), @move_feet(x, y) is called the moment move_head(x, y) is called.

I looked to what the CoffeeScript was compiling to, which is

in the complete: @move_feet(x, y) case to complete: this.move_feet(x, y) and in the complete: @move_feet case to complete: this.move_feet.

Thus, I think it is calling complete: this.move_feet(x, y) as soon as it parses the code. However, how do I get it to delay this execution of the code until the proper time?

Upvotes: 0

Views: 118

Answers (2)

icyrock.com
icyrock.com

Reputation: 28588

Just make another anonymous function:

complete: => @move_feet(x, y)

Here are a couple of samples. First, something like your example:

class Sample
  constructor: (@x, @y) ->

  do_later: =>
    later = => @do_alert(@x, @y)
    setTimeout(later, 2000)

  do_alert: (a, b) =>
    alert([a, b])

a = new Sample(33, 44)
a.do_later()

You don't need classes for this, of course:

later = -> alert("hello")
setTimeout(later, 1000)

Note that if you want this to be preserved (e.g. inside a class), you need to use =>, otherwise -> will be OK. Basically, here later is an anonymous function that when called will run it's body (alert("hello") in the above case). setTimeout(later, 1000) will effectively do later() in 1000ms.

Upvotes: 2

Chuck
Chuck

Reputation: 237010

When you write move_feet(x, y), yes, that is calling the function move_feet — just like in normal JavaScript. If you just write move_feet, that doesn't call it; it's just a reference to the function. What you want instead is this:

complete: => @move_feet(x, y)

Upvotes: 3

Related Questions