Note that there are some explanatory texts on larger screens.

plurals
  1. POCoffeeScript - pass an anonymous function with parameters
    text
    copied!<p>I can't fugure out how to pass an anonymous function that takes a parameter. Here is my situation:</p> <pre><code>class MyClass constructor: (@a) -&gt; console.log("MyClass: created " + @a) show: -&gt; console.log("MyClass: show " + @a) </code></pre> <p>then, with UnderscoreJS, this works:</p> <pre><code>_.map listOfMyClassObjects, (obj) -&gt; obj.show </code></pre> <p>but I want to wrap the call to map in a separate function for convinience:</p> <pre><code>allMyClass(fun) -&gt; _.map listOfMyClassObjects, fun(obj) </code></pre> <p>so that later I can do:</p> <pre><code>allMyClass((obj) -&gt; obj.show()) </code></pre> <p>but the browser console says:</p> <pre><code>Uncaught ReferenceError: fun is not defined (anonymous function) require../browser.CoffeeScript.run ... </code></pre> <p>What is the correct synthax? Also, is it possible to simplify like this?</p> <pre><code> allMyClass(fun) -&gt; _.map listOfMyClassObjects, obj[fun]() allMyClass(show()) </code></pre> <p><strong>UPDATE:</strong></p> <p>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:</p> <pre><code>allMyClass = (fun) -&gt; _.map listOfMyClassObjects, (obj) -&gt; fun(obj) </code></pre> <p>Still wandering if there is a shorter version of passing the class method to the <code>allMyClass</code> function though.</p> <p><strong>UPDATE2:</strong></p> <p>Simplification is possible like this:</p> <pre><code>allMyClass = (fun) -&gt; _.map listOfMyclassObjects, (obj) -&gt; obj[fun]() allMyClass("show") </code></pre> <p>Passing arguments to the <code>fun</code> would require passing more arguments all in all.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload