0

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.

4

1 回答 1

0

是的,您发布的代码是正确的翻译。“ jstocoffe.org ” 是一个很好的网站(尽管报告了一些错误),您可以使用它来将 JavaScript 转换为 CoffeeScript,反之亦然。

我不确定为什么它不起作用,因为您说表格行变得“不可点击”,因为您在@muistooshort 的建议之后发布的代码应该可以工作。我这样说的原因是因为您没有在这里操作 DOM,data-link当文档准备就绪时,您已将 click 事件附加到具有属性的表行(这是$ ->),这应该按预期工作,因为后退按钮和整页刷新重新加载DOM。

对于动态添加的内容(或者在前面提到的 DOM 操作的情况下),您需要使用 jQuery on方法(替换旧的live方法)通过父级或 DOM 树中的元素将事件绑定到“选择器”。阅读 jQuery 的“ on ”方法,它不仅对这个问题有用,而且对你将来要处理的任何事件处理都有用。

但是,对于这个问题,您可以尝试以下方法:

$ ->
  $(document).on 'click', 'tr[data-link]', (evt) -> 
    window.location = this.dataset.link

希望这可以帮助。

于 2013-09-08T00:17:04.060 回答