Someone on the RubyRogues podcast once said “Learn CoffeeScript because CoffeeScript writes better javascript than you do.” Sorry, can’t remember who said it…
So, I took a very simple WORKING javascript function:
togglingii.js
function pdtogglejs(id) { $('div .partybackground').removeClass("hidden"); }
Which is being called by this line:
<a href="#" class="dctoggle" onclick="pdtogglejs('partybackground')">Read More...</a>
Then I converted it into this coffeescript:
toggling.js.coffee
pdtogglecs(id) ->
jQuery('div .partybackground').removeClass("hidden")
and changed the html to reference the pdtoggle*c*s instead of pdtoggle*j*s.
I can see BOTH of them just fine in my application.js file:
(function() {
pdtogglecs(id)(function() {
return jQuery('div .partybackground').removeClass("hidden");
});
}).call(this);
function pdtogglejs(id) { $('div .partybackground').removeClass("hidden"); }
;
(function() {
}).call(this);
However, only the pure javascript works. The coffeescript always returns Uncaught ReferenceError: pdtogglecs is not defined.
Based on other stackoverflow questions it must be some sort of namespace error. Probably because of the way pdtogglecs is, itself, inside of a function?? However, I have tried defining the coffeescript function with: window.pdtogglecs, this.pdtogglecs, root.pdtogglecs and the coffescript one always fails with that error.
What am I missing??
Thanks!!
You have two problems, one is a bit of CoffeeScript syntax confusion and the other is the namespace problem that you know about.
We’ll start by sorting out your syntax confusion. This:
is interpreted like this:
So when given this:
CoffeeScript thinks you’re trying to call
pdtogglecsas a function withidas an argument. Then it thinks thatpdtogglecs(id)returns a function and you want to call that function with your-> jQuery(...)function as an argument. So it ends up sort of like this:And that’s nothing like your original JavaScript. You want to create a function named
pdtogglecswhich takesidas an argument and then runs your jQuery stuff:You can see what’s going on by looking at the generated JavaScript.
The namespace problem is easy and you can probably figure that out based on the other question you found. However, I’ll take care of it right here for completeness.
CoffeeScript wraps each
.coffeefile in a self-executing function to avoid polluting the global namespace:That wrapper makes everything scoped to the
.coffeefile. If you want to pollute the global namespace then you have to say so:You can also say:
but I prefer the explicitness of directly referencing
window, that also saves you from worrying about what@(AKAthis) is when you’re code is parsed.