Rails 3.1和Twitter Bootstrap模式不好玩吗?

时间:2012-03-19 21:09:53

标签: javascript ruby-on-rails-3.1 twitter-bootstrap

我正在撕掉我的头发:

我正在尝试使用Twitter Bootstrap模式(v.1,而不是2)通过AJAX发布评论,使用div的标准TB模态属性:

<div class="modal hide fade" id="commentModal">
<div class="modal-header">
    <a href="#" class="close">×</a>
    <h3>Say Something</h3>
</div>
<div class="modal-body">
    <%= render 'common/error_messages', :target => @comment %>
    <%= form_for [@commentable, Comment.new], :remote => true do |f| %>
      <%= f.hidden_field :user_id, :value => current_user.id %>
      <%= f.text_area :content, :size => "84x5" %>
</div>
<div class="modal-footer">
    <%= f.submit "Comment", :class => "btn primary",:id => "submitButton" %>
</div>
    <% end %></div>

单击该链接会触发模态,并且是否删除remote => true帖子被创建正常(一个重新加载,另一个没有)。但我似乎无法让create.js.erb动作解雇任何javascript,甚至只是为了隐藏模态,更不用说附加评论了:

$('#commentModal').modal('hide');

但是,如果我劫持了click事件,我可以隐藏模态:

$(document).ready(function() {
$('#submitButton').click(function(){
    $('#commentModal').modal('hide');
    return false;
});

});

当然,这会破坏通过创建动作传递给js的典型Rails结构。

有谁能告诉我如何使用Twitter Bootstrap模式通过AJAX发表评论?一个附带条件:评论发布方法需要与模型无关,因为我想在一堆模型上使用代码(多态关联)。

或者让我们首先向我展示如何通过控制器动作解雇怪胎......

一如既往,谢谢。

1 个答案:

答案 0 :(得分:1)

为了感兴趣的人,以上链接对于我弄清楚如何使这项工作至关重要。以下是我的create.js.erb文件的最终版本,基于这些解释。特别感兴趣的是与模态的绑定,特定于Bootstrap:


var el = $('#new-comment-form');

<% if @comment.errors.any? %>

  // Create a list of errors
  var errors = $('<ul />');

  <% @comment.errors.full_messages.each do |error| %>
    errors.append('<li><%= escape_javascript( error ) %></li>');
  <% end %>

  // Display errors on form
  el.find('.modalerrors').html(errors).slideDown();
  el.find('.modalerrors').delay(5000).slideUp();


<% else %>


$('#commentModal').modal('hide');

// Clear form
el.find('input:text,textarea').val('');
el.find('.modalerrors').empty();

// Render a partial to display the comment here-- "prepend" if you want the most recent first, "append" if you want it last
// You must hide the rendered comment before prepending to show it with an effect
// Bind the show effects to when the modal is 'hidden' -- Use 'one' to avoid duplication if someone makes multiple comments before reloading

  $('#commentModal').one('hidden', function () {
     $('<%= escape_javascript(render( @comment )) %>').hide().prependTo('#comments').show('drop',{}, 500, function() {
        $(this).effect("highlight",{color:"#C3FFB5"}, 2000);          
     });
  });

<% end %>
相关问题