jQuery CRUD deletion patterns
July 22nd, 2008
javascript
jQuery
Like a lot of rubyists, I've been playing with jQuery and lov'in it. Here is a little pattern I've been using to generically handle ajax deletion of resources through jQuery.
How are you doing this? Is there a better, cleaner or simpler way?
// ajaxify CRUD delete links
$('a.crud_delete_link').livequery('click', function(){
if (!confirm('Are you sure?'))
return false
var self = this
$.ajax({
// window.location.href should be ok most of the time unless the resource is nested...
// in that case use the rel attribute
url: $(self).attr('rel') != '' ? $(self).attr('rel') : window.location.href,
data: { _method: 'delete' },
type: 'POST',
success: function() {
if ($(self).hasClass('hide_li')) {
$(self).parents('li').fadeOut('fast')
} else {
// trim off record identifer and return to "index" page or refresh page
// example: /admin/clusters/1 => /admin/clusters
// example: /account/logo => /account/logo
var parts = window.location.pathname.match(/^(.*)\/(\d+)$/)
window.location = (parts == null) ? window.location : parts[1]
}
}
})
return false
})


Commenting is closed for this article.