0

I am building a web app using Ruby on Rails. I would like to add some Javascript to a CoffeeScript file

var month = <%= @pin.duedate.month %>;
 var day = <%= @pin.duedate.day %>;
 var date = new Date(year, month, day);
 $("#due_date_timer").countdown({until: date});

At the moment my CoffeeScript file (pins.js.coffee) includes this:

$ ->
 $('#pins').imagesLoaded ->
 $('#pins').masonry
 itemSelector: '.box'
 isFitWidth: true

What is the proper way to include the Javascript into a CoffeeScript file?

Update Followed Amadan's direction In pins.js.coffee

$ ->
 $('#pins').imagesLoaded ->
 $('#pins').masonry
 itemSelector: '.box'
 isFitWidth: true
 year = <%= @pin.duedate.year %>
 month = <%= @pin.duedate.month %>
 day = <%= @pin.duedate.day %>
 date = new Date(year, month, day)
 $("#due_date_timer").countdown({until: date})

I get an error

ExecJS::ProgramError 
 unexpected =
 year = <%= @pin.duedate.year %>
asked Aug 12, 2014 at 5:44
1
  • 1
    You have a whitespace problem, your indentation defines your block structure so you need to be consistent with it. Commented Aug 12, 2014 at 6:14

3 Answers 3

2

The CoffeeScript equivalent of your code is exactly the same, but without var and ;.

answered Aug 12, 2014 at 6:02
Sign up to request clarification or add additional context in comments.

1 Comment

<%= ... %> are neither JavaScript nor CoffeeScript; you need to pass them through ERb before you use them (and in CoffeeScript's case, before compiler gets to work on it). It is not trivial. I suggest including those in your HTML template as a separate script tag, defining a global variable you can use in your CoffeeScript.
1

If you have existing javascript code can try following ...

http://js2coffee.org/

which will convert javascript code to coffee script.

answered Aug 12, 2014 at 5:51

3 Comments

Tried that but it doesn't recognize the js code since I have <%= @pin.duedate.month %> in it
i don't think you can use rails controller variable in coffee script. if you want to pass ruby variable to javascript, select html element from your coffee script and bind with jquery.val()...see here -> api.jquery.com/val
Yes thats why i'm trying to figure out how to change the code so that CoffeeScript understands it.
1

You can embed vanilla javascript in your coffeescript by using backticks.

http://coffeescript.org/#embedded

answered Aug 12, 2014 at 6:01

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.