I am trying to add some JavaScript code in my Ruby on Rails application. I have already created for me, some js.coffee files for each view in my assets. Since, I am not familiar with the CoffeeScript I just passe some ordinary JavaScript/jQuery line in the file, such as:
if ($('#cart').length == 1) { $('#cart').hide("blind", {direction: "vertical" }, 1000); }
$('#cart tr').not('.total_line').remove();
but the following error was thrown:
Error: Parse error on line 1: Unexpected 'POST_IF' (in /home/gotqn/Aptana Projects/depot/app/assets/javascripts/carts.js.coffee)
The source is pointed on
Showing /home/gotqn/Aptana Projects/depot/app/views/layouts/application.html.erb where line #6 raised:
and in this file on line #6 I got:
<%= javascript_include_tag "application" %>
I am new in Ruby on Rails, but what I suppose is happening is that I am not able to write simple JavaScript in the CoffeeScript. If this is true, can I only remove the .coffe extension and be sure that the Rails magic will work and load the file?
CoffeeScript is something that makes even good JavaScript code better. CoffeeScript compiled code can do everything that natively written JavaScript code can, only the code produced by using CoffeeScript is way shorter, and much easier to read.
CoffeeScript tends to run as fast, or faster than hand-written JavaScript.
From the docs on coffeescript.org:
Hopefully, you'll never need to use it, but if you ever need to intersperse snippets of JavaScript within your CoffeeScript, you can use backticks to pass it straight through.
So yes, you can use JavaScript in CoffeeScript - just surround it in backticks:
`function greet(name) {
return "Hello "+name;
}`
# Back to CoffeeScript
greet "Coffee"
# => "Hello Coffee"
hello = `function (name) {
return "Hello "+name
}`
hello "Coffee"
# => "Hello Coffee"
It's highly advisable that you just convert your code to CoffeeScript instead, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With