2012-07-20 51 views
0

有删除帖子的链接:重新绑定行动

<a id="post_232_destroy" class="postDestroy" rel="nofollow" data-remote="true" data-method="delete" data-confirm="Are you sure?" href="/someurl">Delete</a> 

的JavaScript(由coffescript编译):

function() { 

    jQuery(function() { 
    return $("a.postDestroy").bind("ajax:success", function(event, data) { 
     $('#post_' + data.post_id).remove(); 
    }).bind("ajax:error", function() { 
     alert('Please try again'); 
    }); 
    }); 

}).call(this); 

我添加通过AJAX新后,所以绑定删除按钮丢失,为每个最近添加的帖子。帖子被删除,但ajax:成功没有被调用,所以div不会被删除。 我怎样才能再次绑定它?

回答

0

在每次添加新帖子后,您可以解除绑定所有帖子,然后重新绑定。

$("a.postDestroy").unbind("ajax:success"); 
$("a.postDestroy").unbind("ajax:error"); 
$("a.postDestroy").bind("ajax:success", function(event, data) { 
    $('#post_' + data.post_id).remove(); 
}).bind("ajax:error", function() { 
    alert('Please try again'); 
}); 
}); 

编辑: 尝试使用,而不是 “绑定” jQuery的 “活” 的功能:

$("a.postDestroy").live("ajax:success", function(event, data) { 
    $('#post_' + data.post_id).remove(); 
}).live("ajax:error", function() { 
    alert('Please try again'); 
}); 
}); 
+0

这是一些解决方案,但它不是很干。成功和错误的行动有点复杂,我只是修剪它们使代码更具可读性。 – Artur79 2012-07-20 13:13:22

+0

请参阅再次编辑的文章。 – 2012-07-24 12:13:14

+0

对不起,我不明白 – Artur79 2012-07-25 11:23:05