views:

731

answers:

2

I'm trying to make a threaded comments system that behaves like Reddit's: I click "Reply" on a comment, a form shows up. This form has a "Cancel" button that removes the form, going back to the original state.

I'm trying to achieve that with one link_to_function that adds the form, and the form itself has a button_to_function to remove itself and the form. So the javascript generated by link_to_function needs to have escaped HTML with escaped javascript in it and, for some reason, it's not working (clicking "Reply" doesn't do anything). It works fine if I don't add the "Cancel" button. Here's what I have:

<!-- comments/_comment.html.erb -->
<div id="comment_<%= comment.id %>">
  <%= h comment.content %>
</div>

<div id="reply_comment_<%= comment.id %>"></div>

<%= link_to_function 'Reply' do |page|
      page.replace_html "reply_comment_#{comment.id}",
        render(:partial => 'comments/form', :locals => {:comment => comment,
               :commentable => comment.commentable})
    end
%>

and:

<!-- comments/_form.html.erb -->
<% form_tag(comments_path) do %>
  <%= hidden_field_tag 'comment[parent_id]', comment && comment.id %>
  <%= hidden_field_tag 'comment[commentable_id]', commentable.id %>
  <p>
    <%= text_area_tag 'comment[content]' %>
  </p>
  <p>
    <%= submit_tag 'Send' %>
    <% if comment %>
      <%= button_to_function 'Cancel' do |page|
            page.replace_html "reply_comment_#{comment.id}", ''
      end
       %>
    <% end %>

  </p>
<% end %>

What am I doing wrong?

A: 

Although this is technically possible to do exactly as you've specified, I think there's a bug in the encoding because you've got JavaScript in the JavaScript. I'm sure there's a Yo Dawg joke in there somewhere. The second bit of inner JavaScript is probably not quoted correctly.

What you might do instead of using a replace_html function is to simply have the partial set to hidden, then toggle visibility off and on.

Alternatively you can try and fix the encoding through whatever means necessary.

I'm just supposing here. If you could post the output of this it would be easier to say for sure.

tadman
A: 

I am not sure exactly why what you are doing isn't working, but here is an alternate way to do what you are trying to do. Instead of inserting and removing the text from inside the DIV, you could just do a Show/Hide on that element (I removed the form stuff, but the format is roughly the same):

<!-- comments/_form.html.erb -->
   <%= button_to_function 'Cancel', "$('reply_comment_blah').hide()" %>
</p>

<!-- comments/_comment.html.erb -->
<div id="comment_blah">
  Hello!
</div>

<div id="reply_comment_blah", style="display: none;"><%= render :partial => 'form' %></div>

<%= link_to_function 'Reply' , "$('reply_comment_blah').show()" %>
Summit Guy