I’m currently working on a PhoneGap application that uses jQuery, jQuery mobile and a lot of XML. This has been handed to me as the guy who started working on this isn’t around anymore (but I won’t go into that). Okay, an overview… I have a page that reads from an XML file and then uses the returned data to inject images and information of available products. When the user clicks on one of these images I wish to display a dialog… this is easy I just use the following (the dialog is a div within my page not a separate file)
$('#entry_level_phones img').live("click", function(){
$.mobile.changePage("#popupEntry", { role: "dialog"});
});
Okay, I now wish to extend this so when a specific image is clicked I read the same XML file and retrieve more information on the chosen product. This information is formatted, injected as innerHTML into the dialog div and displayed… something like so…
$('#entry_level_phones img').live("click", function(){
// I know the ID of what was clicked using this.id!
$.ajax({
type : 'GET',
url : 'hardware.xml',
dataType : 'xml',
success : getProduct(this.id)
});
});
function getProduct(productID){
productContent = "";
// code to parse through XML and format using the passed productID to locate the relevent info
productContent = outFromParsingData;
$("#popupEntry").html(productContent);
$.mobile.changePage("#popupEntry", { role: "dialog", "test":"test" });
}
now the problem is I need to pass the relevant id (this.id) to the success callback. Normally you would just state the function name and the returned xml from the ajax call is passed through (I still don’t understand how and why).
success : getProduct // this is ajax call
getProduct(xml) // here's the returned xml passed as an argument
with the amends above I can read the returned XML but I don’t have my chosen ID… so finally my question… how do I pass the id and xml to my getProduct function? Many thanks.
Your approach of reloading the same XML each time the image is clicked sounds pretty inefficient to me. If you’ve already loaded the XML to create your images and the related content, would it not make more sense either to store the relevant information associated with each image on the element itself using a data attribute, or store the XML data in a variable and look up the relevant entry with the ID when the image is clicked?
But to answer your question, if you define the handler within the request you can use a closure and variables declared within the scope of your click handler will be available within the scope of the AJAX handler: