crcerror
crcerror

Reputation: 119

CoffeeScript - function runnning but it "is not a function"

appreciate if you help. I have simple function to show (or hide) elements one by one, and it is written in CoffeeScript. The function works great, but my Chrome throws this message in console

"Uncaught TypeError: elemRoll(...) is not a function"

 elemRoll = (elemName, delayDuration, animationDuration) -> 
    		amount = $(elemName).length
    		$(elemName).each (amount) ->
    			$(this).delay(delayDuration * amount).animate { 'opacity': 1 }, animationDuration

$(document).ready -> 
    	do elemRoll '.epoch-container .epoch-item', 190, 160

Upvotes: 1

Views: 191

Answers (1)

mu is too short
mu is too short

Reputation: 434945

You don't need do to simply call a function and rarely would you want to use do for that purpose. Your ready-handler should simply be:

$(document).ready -> 
  elemRoll '.epoch-container .epoch-item', 190, 160
  # No `do` in here

CoffeeScript's do is meant to immediately execute an anonymous function:

CoffeeScript provides the do keyword, which immediately invokes a passed function, forwarding any arguments.

Generally it is used as a loop body when you need closure wrappers:

for e in array
  do (e) -> ...

You can also use it to execute an anonymous function outside a loop:

do (a) -> ...

becomes this JavaScript:

(function(a) { /* ... */ })(a);

You can also use it to execute an argument-less function without the parentheses so do f becomes f().

Your problem is that this:

do a b

is interpreted as

do a(b)

which becomes this JavaScript:

a(b)();

so your:

do elemRoll '.epoch-container .epoch-item', 190, 160

is the same as writing:

f = elemRoll '.epoch-container .epoch-item', 190, 160
do f

and CoffeeScript is assuming that elemRoll '.epoch-container .epoch-item', 190, 160 will return a function.

Also, you need to be very careful and consistent with your whitespace or very confusing things can happen.

Upvotes: 2

Related Questions