2017-01-27 175 views
0

请问能否告诉我,如何在destroy方法结束前删除对象。当我使用下一个模式时,当照片被删除时删除对象会发生,但它需要1或3秒或更长时间。Rails破坏js.erb

_form(编辑操作)

<% listing.photos.each do |photo|%> 
    <%= image_tag photo.image.thumb, class: 'thumbnail', id: "test"%> 
    <%= link_to "remove", photo_path(photo),class: 'btn btn-primary', method: :delete, data: { confirm: 'Are you sure?' }, remote: true %> 

destroy.js.erb

$('#test').remove(); 

如何使用这种模式

_form:

<div id="test_<%= photo.id %>"> 
    <%= image_tag photo.image.thumb, class: 'thumbnail'%> 
    <%= link_to "remove", photo_path(photo),class: 'btn btn-primary', method: :delete, data: { confirm: 'Are you sure?' }, remote: true %> 

Destroy.js .erb:

$('#edit_image_<%= @photo.id %>').remove(); 

回答

0

有一个更清洁的方式做到这一点没有js.erb模板:

<div class="photo"> 
    <%= image_tag photo.image.thumb, class: 'thumbnail'%> 
    <%= link_to "remove", photo_path(photo),class: 'destroy btn btn-primary', method: :delete, data: { remote: true, type: 'json', confirm: 'Are you sure?' } %> 
<div> 

现在只要安装一个Ajax处理程序:

// app/assets/javascripts/photos.js 
$(document).on('ajax:success', '.photo .destroy.btn', function(){ 
    $(this).parent('.photo').remove(); 
}); 

和设置您的控制器正确返回响应代码。

class PhotosController 
    def destroy 
    @photo = Photo.find(params[:id]) 
    @photo.destroy! 

    respond_to do |format| 
     format.json do 
     head :no_content 
     end 
    end 
    end 
end 

这样可以使你的客户端逻辑app/assets/javascripts它可以被缓存和精缩,而不是在一堆荣耀脚本标签内蔓延了。

+0

我刚才试过这种方式,但是当我使用'.image .destroy.btn' - 它不工作。只有'.destroy'。当我点击按钮时 - 它会删除所有照片,并在睡眠1-3秒之前(等待来自服务器的响应)。我有数组。 <%Listing.photos.each do | photos |%>。谢谢,请注意。可能有另一种方式吗? –

+0

我刚刚注意到,我做了一个misstake类'photo'和javascript使用'.image'。 – max

1

如果您想要在DOM上删除图片,以避免延迟,您可以在点击“删除”按钮上应用event.preventDefault()。 这将允许您重写“删除”按钮的正常行为。 看看this example关于在原始事件之前执行一些UI操作,然后触发它。

另请注意,从用户界面中删除某些内容并不确定它是否已被删除,这不是一个好主意。这对用户来说不够清楚。因此,也许最好先隐藏图像,并在发生服务器错误的同时摧毁它,然后再显示它并显示一些指导性消息。

UPD

考虑下面的标记

<div id="test_<%= photo.id %>"> 
    <%= image_tag photo.image.thumb, class: 'thumbnail' %> 
    <%= link_to "remove", "#", class: 'remove btn btn-primary', data: { id: photo.id, url: photo_path(photo) } %> 
</div> 

另一个选择是重写remote: true具有独立jQuery.ajax()通话。

$('.btn.remove').click(function() { 
    var $target = $(this).parents('#test_' + $(this).data('id')); 

    $.ajax({ 
    url: $(this).data('url'), 
    method: 'DELETE', 
    beforeSend: function() { 
     $target.hide() # hiding corresponding image 
    }, 
    error: function() { 
     $target.show() # revert hiding on error 
     console.log("Sorry! Couldn't remove image.") # log message 
    } 
    }) 
}) 
+0

使用乐观删除的+1。通过监听'ajax:beforeSend'事件,你可以用rails ujs(remote:true)做同样的事情。 – max