Lee Quarella
Lee Quarella

Reputation: 4732

Calling coffeescript functions from console

Playing a little with coffeescript and Rails 3.1.0.rc4. Have this code:

yourMom = (location) ->
  console.log location

yourMom "wuz hur"

When the page loads, this outputs "wuz hur" properly. But when I try to call

yourMom("wuz hur")

from the chrome js console (as I do sometimes to test normal JS functions), I get a "ReferenceError: yourMom is not defined"

Are functions generated by coffeescript available in this way?

Upvotes: 16

Views: 10466

Answers (4)

sajesh Nambiar
sajesh Nambiar

Reputation: 699

this link might solve your problem Rails - Calling CoffeeScript from JavaScript Wrap your functions in a unique namespace and then you can acess these functions from wnywhere

Upvotes: 0

Sébastien Gruhier
Sébastien Gruhier

Reputation: 644

an easier way to share global methods/variables is to use @ which means this.

@yourMom = (location) ->
  console.log location

yourMom "wuz hur"

Nicer syntax and easier to read, but I don't encourage you to create global methods/variables

Upvotes: 39

liammclennan
liammclennan

Reputation: 5368

I'm not sure about Rails but the CoffeeScript compiler has an option (--bare) to compile without the function wrapper. Fine for playing but it does pollute the global scope.

Upvotes: 2

Jamie Wong
Jamie Wong

Reputation: 18350

This happens because coffeescript wraps everything in a closure. The JavaScript output of that code is actually:

(function() {
  var yourMom;
  yourMom = function(location) {
    return console.log(location);
  };
  yourMom("wuz hur");
}).call(this);

If you want to export it to the global scope, you can either do:

window.yourMom = yourMom = (location) ->
  console.log location

or

this.yourMom = yourMom = (location) ->
  console.log location

Upvotes: 13

Related Questions