Avoiding AJAX Scope Issues in Prototype
April 13, 2006 @ 01:04 am
I haven't seen this covered much, but I really felt it was worth a mention. A lot of people have worked with the prototype library, including myself. One of the most challenging things I've had to do was create an object that could make an AJAX request, and then internalize the response. Calling a function out on the global scope is messy and in poor taste if you can avoid it. I thought back to my Java classes, and remember an almost reflexive style of programming. About an hour later (including reading through prototype's source) I had a working model.
The major players in this design are the XMLHttpCatch object and the Ajax.Request object. Our goal is to call a sending function inside of an instance of myObj, and then have the response be ran in the context of myObj. By default, you cannot refer to "this" inside of the callback, because of scope issues. The solution is to encapsulate the request, and then have a way for the response to find its way back home. We do this by passing the scope down into the XMLHttpCatch object.…