Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use ordinary JavaScript in CoffeeScript file?

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?

like image 896
gotqn Avatar asked Nov 07 '12 18:11

gotqn


People also ask

Why should you use CoffeeScript instead of JavaScript?

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.

Is CoffeeScript slower than JavaScript?

CoffeeScript tends to run as fast, or faster than hand-written JavaScript.


1 Answers

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.

like image 152
redhotvengeance Avatar answered Sep 18 '22 15:09

redhotvengeance