[Javascript] AJAX app causing excessive browser memory usage
Jonathan Buchanan
jonathan.buchanan at gmail.com
Fri May 19 09:53:45 CDT 2006
> The last thing I tried was to create an object:
>
> function xhrObj() {
> this.isXHRBusy = false;
> }
>
> xhrObj.prototype.getList() {
> if (!this.xhr) {
> this.xhr = commonUtils.getHTTPObject();
> }
> if (!this.isXHRBusy && this.xhr) {
> this.xhr.open("GET", "getXMLeventlist.php", true);
> this.xhr.onreadystatechange = this.handleXHRResponse;
> this.isEventListWorking = true;
> this.xhr.send(null);
> }
> }
>
> xhrObj.prototype.handleXHRResponse() {
> if (HTTP_REQ_COMPLETE == this.xhr.readyState) {
> // process the response
> }
> }
>
> When the response function checks readyState, I get a javascript error
> "this.xhr has no properties". I thought I needed to set xhr to
> something either in the constructor or by adding it to the
> xhrObj.prototype, but what would I set it to? Setting it to the
> xmlhttprequest object defeats the purpose of creating and destroying
> it on the fly.
>
> I'm sure I'm just missing something simple...can anybody help me out?
>
> Thanks in advance,
> Rick
The problem in this case is that when handleXHRResponse() is called,
"this" no longer refers to your xhrObj instance. You can use the
built-in call[1] or apply[2] functions to execute the function in the
scope of your xhrObj instance.
To demonstrate usage, here's a function yoinked from the Prototype
library which allows you to do this by extending Function itself:
Function.prototype.bind = function(object) {
var __method = this;
return function() {
__method.apply(object, arguments);
}
}
Usage:
this.xhr.onreadystatechange = this.handleXHRResponse.bind(this);
Alternatively, if you don't want to modify built in objects, you could
use the following form:
function bind(targetFunction, object) {
return function() {
targetFunction.apply(object, arguments);
}
}
Usage:
this.xhr.onreadystatechange = bind(this.handleXHRResponse, this);
Jonathan.
----
[1] http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Function:call
[2] http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Function:apply
More information about the Javascript
mailing list