2

For example i have many comments rendered for the post.

<%= render post.comments %>

And in comments partial i have javascript wich will repeated so many times how many comments i have

_comment.html.erb

<div id="content_<%= comment.id %>"><%= comment.content %></div>
<scr​ipt>$("content_<%= comment.id %>").click(function() { a​lert(​'content of comment <%= comment.id %>'​) });</sc​ript>

What is the best way to avoid repeating javascript in source code? I tried to create *_comment.js.erb* file and put javascript there, but i don't understand how to make it work.

Can anyone please explain me how to solve this problem?

1 Answer 1

3

You can change the implementation to have a single js file under app/assets/javascripts with your script inside. change the selector of the script to match the class of the comments instead of a unique ID. If required, use javascript to read the content of elements, instead of doing this on the server as you do now.

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

4 Comments

But if i will have script in assets/javascripts how can i tell rails that each comment have his own script? Thats why i'm using content_<%= comment.id %>
You're right. The idea is to have the same script for all, and differentiate between the comments in the script code itself. I assume this is the same logic for all the comments, only with different data.
Thanks for helping, but can you please explain more?
in your selector, use class, instead of id (something like: $('.comment')). in the alert, use $(this).attr("id"), or something similar with another attribute in order to fetch the actual data. The code should be roughly something like this: $('.comment').click(function() { a​lert($(this).attr("id")​) });

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.