views:

97

answers:

1

Given an instantiated JavaScript object/class can I make an Ajax call from that class and have the returning success function callback into the caller's object?

Currently I can get the callback to return back into the object, but I lose the "this" property, which kills the state of my object

function BaseConsoleHelper()
{
this._iconIndex = 0;
} 
BaseConsoleHelper.prototype = {
Dispose: function()
{
this._previousIndex = 0;
},
GetVisitConsoleIcons: function(name)
{
    this._iconIndex = 500;

    SampleNamespace.MyService.GetConsoleIcons(name, this.IconsGenerated);
},
IconsGenerated : function(result)
{ 
    //I should be 500.....but I'm not, cause "this" has become something else
    alert( this._iconIndex );
}
};

BTW I using asp.net ajax 3.5 (and, wow, isn't inheritance different in here than pure JavaScript)

+1  A: 

Change this line:

SampleNamespace.MyService.GetConsoleIcons(name, this.IconsGenerated);

to:

SampleNamespace.MyService.GetConsoleIcons(name, 
    Function.createDelegate(this, this.IconsGenerated)
);

See this article for more examples of retaining references to this within Web Service calls.

Crescent Fresh
thx, just discovered the same thing.Followup Question: Function.createDelegate vs. Type.createDelegate?
BozoJoe
@Alex: They're the same thing (literally). MS AJAX aliased `Function` as `Type`, but officially you're supposed to do `Function.createDelegate` instead of `Type.createDelegate`.
JPot