I have a series of anonymous jQuery/javascript functions for click events which have to be dynamically added as a delegate function to content returned by ajax commands and i’m finding I am copy pasting a lot of code which is difficult to manage.
For example, in the code below is a delete button which is attached to all the delete buttons when the page first loads. There is also code which adds an item to a database and then adds an element to the DOM which contains a delete button. The delete event handler function needs to be added to this new button as it wasn’t there when the page first loaded, this is done through the use of the delegate function – this works perfectly well but I am having to copy paste a lot of code to achieve the delegates and it is making the code difficult to manage. Is there any way to add the delegate function without copy pasting it in?
I have tried creating a separate function for delete and calling it in the same way you would in C but couldn’t get that to work. I have also considered breaking the code up in to smaller blocks and then using php to write the javascript but that seems like a rather complex things for what I think should be simple to do. Is there another way?
Any help would be great, apologies if it is a simple fix
$(document).ready(function(){
$("a.delete").click(function(){
//do stuff
$.ajax({
type: "GET",
url: url,
success: function(msg){
//do more stuff
}//end of success function
});//end of ajax*/
});//end of delete button
$("button#addItem").click(function(){
//do stuff
$.ajax({
type: "GET",
url: url,
dataType: "json",
success: function(msg){
//do stuff
//form the id for the delete button
var buttonID = "#delete" + msg.id;
//need to attach the delete function to the new button to make sure the function is there
$("body").delegate(buttonID, "click", function(){
//do stuff
$.ajax({
type: "GET",
url: url,
success: function(msg){
//do stuff
}//end of success function
});//end of ajax*/
});//end of delegate function attaching to the delete button
}//end of success function
});//end of ajax
});//end of add button
});//final close
There are a couple of things you can do:
Named functions
There’s never any reason to duplicate exactly the same function in more than one place. Instead, give the function a name and refer to it from two places:
And/or use event delegation
But in many cases you can also use event delegation to hook up a handler that will get used even for elements that haven’t been created yet, using
liveor (if possible)delegate:Or ideally, hook this up on a container that contains all of these delete links:
That tells jQuery to hook the “click” event on the document, and then when the click occurs to see if the actual element clicked matches the selector “a.delete” and if so, fire the handler.
As of jQuery 1.7, you’d use
onrather thanlive:Or ideally, if there’s some more specific container than the document body:
(Note that the order of arguments is different from
delegate.)