Sometimes I have multiple elements which need a click
callback function with some common functionality, and have implemented doing so as the following:
function deleteRecord(elem, url, type) {
if (confirm("Are you sure you wish to delete this "+type+"?")) {
$.ajax({
type:'DELETE',
url: url,
dataType: 'json',
success: function (rsp){
$(elem).closest('tr').remove();
},
error: function (xhr) {
alert('Error: '+xhr.responseJSON.message);
}
});
}
}
$("#manual-list img.delete").click(function() { deleteRecord(this, '/1.0/manuals/'+$(this).closest('tr').data('id'),'manual')});
Instead of using a function, I've been trying to create a very simple plugin. I've successfully created flexible jQuery plugins as described by https://learn.jquery.com/plugins/advanced-plugin-concepts/, however, I think doing so for these types of applications is overkill, and wish to use a drop-dead plugin design pattern. My latest attempt is below, however, I have been unsuccessful passing it the url
argument which is derived by the element to which the plugin is applied.
What options are available for a very simple and concise jQuery event driven plugin?
(function( $ ){
$.fn.deleteRecord = function(url, type) {
console.log('init', url, type, this, url.call(this, url, type));
this.click(function(){
//Confirm that this.each(function(){...}) is not required
console.log('onClick', url, type, this, url.call(this, url, type))
if (confirm("Are you sure you wish to delete this "+type+"?")) {
console.log('onConfirm', url, type, this, url.call(this, url, type))
var e=this;
$.ajax({
type:'DELETE',
url: url.call(this, url, type),
dataType: 'json',
success: function (rsp){
$(e).closest('tr').remove();
},
error: function (xhr) {
alert('Error: '+xhr.responseJSON.message);
}
});
}
})
return this;
};
})( jQuery );
$("#manual-list img.delete").deleteRecord(function(){'/1.0/manuals/'+$(this).closest('tr').data('id')},'manual');
Aucun commentaire:
Enregistrer un commentaire