This is related to the following question but I would like to use coffeescript instead of javascript for comparability with the defaults in Rails 4.
The starting point is code provided in answers to an earlier question: Making a table row into a link in Rails
The view ERB code contains a table generator with the following code:
<% @songs.each do |song| %>
<tr data-link="<%= edit_song_path(song) %>">
<td><%= song.Name %></td>
<td><%= song.Group %></td>
</tr>
<% end %>
The <tr data-link="<%= edit_song_path(song) %>">
line is based on the answer given in the above linked question.
I have the follwing in the songs.js.coffee file:
$("tr[data-link]").click ->
window.location = this.dataset.link
This is my translation for the javascript in the answer from Mark Berry. I have also tried the other suggestions such as window.location = $(this).data("link")
.
When the page is loaded the table rows are not clickable. If I replace the action of setting the window.location
with an alert, I get the alert dialog when the page loads and not when the user clicks a table row.
The above coffeescript code is the only code in the song.js.coffee file. Am I missing anything that needs to be wrapped around the code?
Partial answer: Adding $ ->
before the original coffeescript code as suggested in the first comment does make the table rows selectable ONCE. I believe from other reading that the dollar sign variable has been made an alias to jQuery (an example of this is in the idioms chapter of The Little Book on Coffeescript: http://arcturo.github.io/library/coffeescript/04_idioms.html).
Unfortunately, after the page is loaded one table row can be selected causing the edit page to be displayed, but if the user returns to the page, either using the back button on the browser or a link back to the page, the table rows are no longer selectable.
The new coffeescript code is:
$ ->
$("tr[data-link]").click ->
window.location = this.dataset.link
Is the above code the correct translation from javascript to coffeescript. I am new to both scripting languages.
Is there a different answer to making a clickable table row using coffeescript in Rails 4?
Thank you.