I spent a lot more time than necessary today trying to figure out how to use Yahoo’s Ajax object. The first minor setback occurred because I didn’t know that the callback variable MUST be defined after the success and failure functions. I am still not really sure why, but now that I know how it works, I don’t really care. The next problem that took a little time to figure out was how to keep all the javascript code manageable. Assuming that I build a decent sized application with a decent number of Ajax requests, my javascript file could get pretty large. So I decided that I would organize my code as seen below.
var sentItems =
{
success: function(o)
{
var sent =
document.getElementById
('items_sent_'+sentItems.swap_id).
innerHTML = "Sent!";
},
failure: function(o)
{
alert(o.statusText);
},
click: function(url,id)
{
sentItems.swap_id = id;
var cObj = YAHOO.util.Connect.asyncRequest
('GET',url,sentItemsCallback,null);
}
}
var sentItemsCallback =
{
success: sentItems.success,
failure: sentItems.failure
}
I don’t know any of the jargon for psuedo-Object Oriented javascript, so I won’t even try. But basically, my “click” function is called from my HTML onclick (using, say, sentItems.click(this.href,some_id). I tried putting the callback function into my “object”, but couldn’t get it to work. In my own mind, the code will be in a lot better order if I can figure out how to get it into there, so I will keep trying.
I know that Yahoo’s callback function definition allows for an argument handler, and I could get it to work with static information, but I didn’t know where to begin in getting dynamic information set to the argument. To overcome this, I simply created “object variables” on the fly as I needed them. Check out the click function where I set “sentItems.swap_id = id” and then in the success function where I use the variable. It all works!
Nice work Travis. I’d like to see your working code one day.