2

I currently have a page with a bunch of lists, where each list has an ability to add a comment.

Here's the _new.html.haml partial that's generated and end of every list

<div class="comment add-comment row-fluid">
  <div class="avatar">
    <img alt="Admin User1" src="http://localhost:3000/assets/DDDDDD.png">
  </div>
  <div class="message">
    <form accept-charset="UTF-8" action="/suggestions/50057a3160de7d361d000061/comments" class="new_comment" data-remote="true" id="new_comment" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" value="✓" type="hidden"><input name="authenticity_token" value="vVw7kLNGF4AiXmOMjryPDI70Mz5paZnW3usdgzxLsik=" type="hidden"></div>
    <fieldset>
      <div class="control-group">
        <div class="controls">
          <textarea cols="40" id="comment_content" name="comment[content]" placeholder="Add a comment..." required="required" rows="20"></textarea>
        </div>
      </div>
      <input class="btn btn-primary" name="commit" value="Post" type="submit">
    </fieldset>
</form>
  </div>
</div>

I was able to use Unobtrusive JavaScript to create the comment, but when I load create.js.haml, I'm not sure what DOM object to attach it to.

In my comments/create.js.haml, I have

$(".add-comment").before("#{escape_javascript(render partial: "comments/show", locals: { :comment => @comment })}")

Obviously this doesn't work since add-comment class is common to all lists. Is there a way that I can append the content of what I just created to the correct list and show a new add comment section?

4

1 回答 1

0

I finally was able to fix it. Debugging Unobtrusive JavaScript is bit harder than regular JS. Thank goodness to Google Chrome Dev Tool's Network feature.

In my View, I added an id

<div class="comment add-comment row-fluid" id="500614e960de7d313a000189">
  ...
</div>  

Then, within create.js.haml, I got the ID from the variable @commentable, which is passed in by the controller, converts to a DOM element, and then processes some more JS.

var div_id = $('.stream-item').find("##{escape_javascript(@commentable.id.to_s)}")
div_id.find("textarea").val("");
div_id.before("#{escape_javascript(render partial: "comments/show", locals: { :comment => @comment })}")
于 2012-07-19T02:38:38.703 回答