0

I can't fugure out how to pass an anonymous function that takes a parameter. Here is my situation:

class MyClass
  constructor: (@a) ->
    console.log("MyClass: created " + @a)

  show: ->
    console.log("MyClass: show " + @a)

then, with UnderscoreJS, this works:

_.map listOfMyClassObjects, (obj) -> obj.show

but I want to wrap the call to map in a separate function for convinience:

allMyClass(fun) ->
  _.map listOfMyClassObjects, fun(obj)

so that later I can do:

allMyClass((obj) -> obj.show())

but the browser console says:

Uncaught ReferenceError: fun is not defined
  (anonymous function)
  require../browser.CoffeeScript.run
  ...

What is the correct synthax? Also, is it possible to simplify like this?

 allMyClass(fun) ->
    _.map listOfMyClassObjects, obj[fun]()

 allMyClass(show())

UPDATE:

As per Thilo's answer, there was the syntax mistake in the function call. But also, there was a mistake in calling the function on the map iteration result. The working version is this:

allMyClass = (fun) ->
  _.map listOfMyClassObjects, (obj) -> fun(obj)

Still wandering if there is a shorter version of passing the class method to the allMyClass function though.

UPDATE2:

Simplification is possible like this:

allMyClass = (fun) ->
  _.map listOfMyclassObjects, (obj) -> obj[fun]()

allMyClass("show")

Passing arguments to the fun would require passing more arguments all in all.

1
  • 1
    In CoffeeScript the class body itself is a function expression that gets executed and returns the actual class constructor. So foo = 1 sets a variable within the scope of the Class body function expression itself. While foo: 1 sets a foo property with a value of 1 on the class prototype. Commented Jul 22, 2012 at 18:19

1 Answer 1

2

Did you mean to define a function

allMyClass = (fun) ->
   _.map listOfMyClassObjects, fun(obj)

or method

allMyClass : (fun) ->
   _.map listOfMyClassObjects, fun(obj)

Without the = or : you were just calling allMyClass.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh! Just can't get used to CoffeeScript function notation ))) That's it! However, there was one more issue with my code, which I have depicted in the update.
For any kind of syntax error, paste the offending lines into "Try CoffeeScript" and see what the JS looks like. jashkenas.github.com/coffee-script

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.