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?
-
5Must resist urge to make mom joke....Jesus Ramos– Jesus Ramos2011年07月20日 01:37:09 +00:00Commented Jul 20, 2011 at 1:37
-
1Sigh. Duplicate of stackoverflow.com/questions/6089992/…. See also stackoverflow.com/questions/6099342/….Trevor Burnham– Trevor Burnham2011年07月20日 13:13:12 +00:00Commented Jul 20, 2011 at 13:13
-
Sorry Trev, missed those. What is best practice after realizing your question is a dup, should I just delete it?Lee Quarella– Lee Quarella2011年07月20日 17:54:27 +00:00Commented Jul 20, 2011 at 17:54
-
4@TrevorBurnham "Sigh.": this is a bit obnoxious. Please don't be obnoxious to new people. It's verging on the RTFM attitude from the C++ mailing list days.jcollum– jcollum2013年01月07日 22:15:15 +00:00Commented Jan 7, 2013 at 22:15
-
@LeeQuarella I'd just put "Duplicate of XYZ (Link)" at the top of the post. These days, dupes will get marked as such (with a link to the dupe) and closed pretty quickly.jcollum– jcollum2013年01月07日 22:16:51 +00:00Commented Jan 7, 2013 at 22:16
4 Answers 4
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
1 Comment
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
4 Comments
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.
Comments
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
Comments
Explore related questions
See similar questions with these tags.