Javascript: How to save a link to a request initiator in a handler?

I'm not ordinary Javascript, but I dive in, read the book by Douglas Crockford and write some trivial, useful tidbits like the Chrome and Node.js extensions (note that this question does not apply to any of them).

I'm currently trying to figure out how to save a reference to the object that triggers the AJAX request, that is: after I installed the onload event handler (this is from inside the Chrome extension, so I'm using the XMLHttpRequest base object), is there a way with through which I can return to MyObject in the following example:

 MyObject.prototype = { PerformAction: function() { this.Request = new XMLHttpRequest(); this.Request.open("GET", this.ConstructUrl(), true); // From within ActionResultHandler, 'this' will always be the XMLHttpRequest this.Request.onload = this.ActionResultHandler, this.Request.send(null); } } 

Doing this exactly means that this will be the object of the request, and if I just present the shell:

 this.Request.onload = function() { ActionResultHandler() }; 

well, that is simply not going to do anything, because ActionResultHandler is now beyond the scope. The reason I'm asking here is because I have discovered trivial cases of manipulating callers (e.g. manipulating what this means inside a function), but assuming that OO-ified Javascript and AJAX are literally everywhere, this should be a famous, simple problem, but my google fu can't get me here. In C #, events are triggered in the context of who attaches to them, and not the object that triggers the event, so this does not occur daily. Maybe there is a much better JS template that completely avoids this problem?

0
javascript ajax design-patterns
Jul 07 '10 at 7:45 a.m.
source share
2 answers

It’s not entirely clear to me which variable you want to keep. Here, how would you save the link to MyObject in the onload handler:

 MyObject.prototype = { PerformAction: function() { var MyObjectRef = MyObject, ActionResultHandler = this.ActionResultHandler; this.Request = new XMLHttpRequest(); this.Request.open("GET", this.ConstructUrl(), true); // From within ActionResultHandler, 'this' will always be the XMLHttpRequest this.Request.onload = function () { ActionResultHandler.apply(MyObjectRef, arguments); }; this.Request.send(null); } } 

Edited

Ok, I'm re-reading your question again and it seems like you want to execute an ActionResultHandler in the context of MyObject, so I changed my code to do this.

+3
Jul 07 '10 at 20:57
source share

You tried...

 this.Request.onload = this.ActionResultHandler.apply(this); 

I think what you are looking for (sorry if not). Using .apply(this) will point the ActionResultHandler to an Object .

Discard this peg article while you're on it! It has helped me a lot.

+1
Jul 07 '10 at 20:41
source share



All Articles