> -----Original Message-----
> From: Dan G. Switzer, II [mailto:[EMAIL PROTECTED]
> Sent: Tuesday, March 21, 2006 11:10 AM
> To: CF-Talk
> Subject: RE: JavaScript Scoping Gurus?
> 
> Jim,
> 
> What I've always done to counter this problem is to create an API
> class--which I use to monitor instances of each class and hold "global"
> functionality. For example:

Thanks... but I really hate "tainting" the global scope if I can at all help
it.

I think I've found an answer however.  The problem is that "setInterval()"
runs in context of the window object and that the code sent to it is treated
as a string (it's evaluated every time it's run) so "this" can't be passed.

Instead you can force lexical scoping to be honored by using a proxy
function in the scope of the object - the function reference maintains its
scope since it's "pinned" to the context in which it was created.

Here's how I ended up doing it:

        // Create the Pool
function HTTPRequestPool(ObInstanceCount, IntervalCount) {

        ... lots of other code ...

                // Set a proxy function to maintain scoping when called in
the context of Window
        var ThisPool = this;
        var IntervalProxy = function() { ThisPool.doRequest() };
                // Start the Interval
        window.setInterval(IntervalProxy, IntervalCount);

};

This works a treat.

Note that it's pretty "fragile" in the sense that all those parts are
needed.  Doing the following doesn't work:

var IntervalProxy = function() { this.doRequest() };
window.setInterval(IntervalProxy, IntervalCount);

This doesn't work either (because you must pass a reference to the function
rather than the function call):

var ThisPool = this;
var IntervalProxy = function() { ThisPool.doRequest() };
window.setInterval(IntervalProxy(), IntervalCount);


It's like you have to "pin" and reinforce the reference to the object at
every step.

Considering that I don't feel so bad that it took a while for me to get it.
;^)

Jim Davis


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
Message: http://www.houseoffusion.com/lists.cfm/link=i:4:235870
Archives: http://www.houseoffusion.com/cf_lists/threads.cfm/4
Subscription: http://www.houseoffusion.com/lists.cfm/link=s:4
Unsubscribe: http://www.houseoffusion.com/cf_lists/unsubscribe.cfm?user=89.70.4
Donations & Support: http://www.houseoffusion.com/tiny.cfm/54

Reply via email to