3

Doing a google search gives depreciated answers for older versions of rails or says to use turbolinks. I like the idea of the coffeescript files but don't want to write everything in coffeescript is there a way to have a item.coffee and item.js file so it reads both. I saw this in a rails cast but that video was pretty old and that approach doesn't seem to work now.

If the only way is to use turbolinks to add page specific js to a page how is that done?

1 Answer 1

1

I know the answers to your questions; this might be verbose...


is there a way to have a item.coffee and item.js file so it reads both

Coffeescript is a pre-processor.

In as much the same way as SCSS/SASS, it runs through "coffeescript" code and translates into standardized JS. In short, coffeescript is not a "language" in itself, it's just pseudocode for standard JS.

This means that if you're using a coffeescript extension, you can still use standard JS with it:

#app/assets/javascripts/item.js.coffee
alert("hello"); #-> Js
alert "hello"   #-> Cs

... same functionality.

--

If the only way is to use turbolinks to add page specific js to a page how is that done

It's not the "only" way. It's no way at all:

Instead of letting the browser recompile the JavaScript and CSS between each page change, it [Turbolinks] keeps the current page instance alive and replaces only the body (or parts of) and the title in the head

Turbolinks replaces the <body> of your page if the assets remain the same (it speeds up page load by removing the need to re-initialize the assets each time).

Of course, this is null & void when dealing with different assets.

If you have a different set of assets (different layout etc), Turbolinks will reload as appropriate:

#app/views/layouts/application.html.erb
<%= stylesheet_link_tag :application, (:transactions if controller_name == "transactions") %>

In this case, Turbolinks refreshes the entire page, which will update your assets through the refresh.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the detailed answer.
If I add js coding to a coffee script file it usually breaks. Do i need to declare that it is js coding or something?
What's the filename? .js.coffee should get it working. It's like having erb in your JS - can only be recognized if you use .js.erb

Your Answer

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.