【发布时间】:2011-12-15 04:58:29
【问题描述】:
我正在寻找一种将控制器的全局变量用于这样的咖啡脚本的方法:
控制器:
respond_to :js
def create
@commentable = commentable
@comment = @commentable.comments.build({:comment => params[:comment], :user => current_user})
@comment.save
respond_with(@comment, @commentable)
end
create.js.coffee:
$("#form_#{@commentable.class}_#{@commentable.id}").hide()
这个想法是在一个页面中有几个commentables,并识别当前评论的一个隐藏/显示一个表单来评论它;表单的 id 是使用类和可注释的 id 构建的。此时,如果我尝试使用上面的代码访问一个元素,它不起作用,因为脚本中似乎不存在@commentable。
编辑:
我阅读了here的答案,并尝试了以下方法:
在我的帖子/show.haml
:javascript
var commentable_comments_id;
#post
@post.body
= render :partial => 'comments/list', :locals => {:commentable => @post}
在我的部分 _list.haml
#comments_container
%div{:id => "comments_#{commentable.class}_#{commentable.id}"}
- commentable.comments.reverse_each do |comment|
= render :partial => 'comments/comment', :locals => {:comment => comment}
- if current_user
.add_comment_link{:id => "link_#{commentable.class}_#{commentable.id}"}
#{link_to "Commenter"}
.add_comment{:id => "form_#{commentable.class}_#{commentable.id}"}
= render :partial => 'comments/comment_form', :locals => {:commentable => commentable}
并且在部分 _comment_form.haml
.comment_form
= form_tag polymorphic_path([commentable, Comment]) , :method => :post, :remote => true do |f|
.comment_field
= text_area_tag :comment, params[:comment], :id =>"comment_area", :rows => 4, :cols => 50
.comment_field
= submit_tag "Commenter", :id => "submit_comment_#{commentable.class}_#{commentable.id}", :class => "submit_comment"
在 posts.js.coffee 中:
jQuery ->
commentable_link_id = null
commentable_form_id = null
hide_element_by_id = (id_name) ->
$("#"+id_name).hide()
show_element_by_id = (id_name) ->
$("#"+id_name).show()
$('.add_comment_link').click ->
currentId = $(this).attr('id')
if(commentable_link_id != null && commentable_form_id != null)
hide_element_by_id(commentable_form_id)
show_element_by_id(commentable_link_id)
commentable_link_id = currentId
commentable_form_id = currentId.replace("link", "form")
hide_element_by_id(commentable_link_id)
show_element_by_id(commentable_form_id)
commentable_comments_id = currentId.replace("link", "comments")
false
$('.submit_comment').click ->
if(commentable_link_id != null && commentable_form_id != null)
hide_element_by_id(commentable_form_id)
show_element_by_id(commentable_link_id)
所以当用户点击链接添加评论时,它会隐藏之前的评论表单(如果有的话),它会显示新的正确表单,构建 cmets'container 的 id(例如 cmets_Post_3)并存储它在页面的全局 js 变量中:
commentable_comments_id = currentId.replace("link", "comments")
然后在 create.js.coffee 中,我尝试使用此变量将新评论附加到存储的容器中:
$('<%= escape_javascript(render(:partial => @comment))%>')
.appendTo("#"+commentable_comments_id)
.hide()
.fadeIn()
我认为这是不正确的,因为最后一个操作(带有淡入淡出的追加)不起作用,因此不能初始化全局变量 commentable_cmets_id 或其他...
【问题讨论】:
标签: ruby-on-rails-3.1 coffeescript