Avoiding AJAX Scope Issues in Prototype

April 13, 2006 @ 01:04 am

2 Comments

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.

Hopefully other people will find this useful, as occasionally it is not practical to have globally scoped functions for onComplete, and you want access to all the proper this.methodName() calls. I thought about moving the catch object into myObj as a function definition during initialize, but the current model is a bit more reusable.

In response to "Avoiding AJAX Scope Issues in Prototype":

  1. May 04, 2006 at 5:05 am

    Man, it’s your posts like these that make me feel like I know absolutely nothing about javascript/PHP. xD
    When/where did you learn all this stuff?
    My greatist achivement so far is making a fairly good (if painstakingly slow) version of Gaia’s avatar sysetm in PHP. Well, the first system. I haven’t implemented poses or when-this-equips-unequip-these-slots functions, but I can happily say it’s a damn sight better than magivolve’s system! ;3
    I did it for one of my GCSE ICT projects, actually. I’ve got the full system testing images lying around somewhere if you want to see it.
    Anyway I want to get to your level. D:
    Any pointers to gain your sort of knowlage? :3

  2. November 14, 2006 at 1:54 pm

    very good, I liked it :)

    - Kevin

Leave a Reply:

Commenting is not available in this section entry.