noncom
noncom

Reputation: 4992

CoffeeScript - pass an anonymous function with parameters

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.

Upvotes: 0

Views: 3378

Answers (1)

Thilo
Thilo

Reputation: 262842

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.

Upvotes: 2

Related Questions