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 %> 
1
  • 1
    You have a whitespace problem, your indentation defines your block structure so you need to be consistent with it.CommentedAug 12, 2014 at 6:14

3 Answers 3

2

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

1
  • 1
    <%= ... %> 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.
    – Amadan
    CommentedAug 12, 2014 at 6:36
1

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

http://js2coffee.org/

which will convert javascript code to coffee script.

3
  • Tried that but it doesn't recognize the js code since I have <%= @pin.duedate.month %> in it
    – Cyzanfar
    CommentedAug 12, 2014 at 5:52
  • 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
    – user2473975
    CommentedAug 12, 2014 at 5:54
  • Yes thats why i'm trying to figure out how to change the code so that CoffeeScript understands it.
    – Cyzanfar
    CommentedAug 12, 2014 at 5:56
1

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

http://coffeescript.org/#embedded

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.