views:

101

answers:

1

Hi,

I'm trying to keep as much OO as possible, but ASP.NET AJAX seems to be doing something strange after returning from the server...

function Person( personId ) {
var id = personId;
var firstName;
var lastName;

this.initializeStep1 = function() {
    PeopleServices.getFirstName(id, this.initializeStep2);
}

this.initializeStep2 = function(foundFirstName) {
    alert(foundFirstName);
    firstName = foundFirstName;
    PeopleServices.getLastName(id, this.initializeStep3);
}

this.initializeStep3 = function(foundLastName) {
    alert(foundLastName);
    alert(firstName);
    lastName= foundLastName;
} 

this.initializeStep1();

}

This is the basis of it. So basically it is creating a person and retrieving their first and last name from the server in order to initialize the person.

When I create a new person, it goes through initializeStep1, calls the server webmethod getFirstName, and eventually reaches initializeStep2. the alert(foundFirstName); works, it alerts the name that was found and it is correct... now after setting the private variable firstName to what was found, I make a second call to the server...

This time, it does not reach initializeStep3, and I know it shouldn't have failed on the server end because even if I replace the line

PeopleServices.getLastName(id, this.initializeStep3);

with

PeopleServices.getFirstName(id, this.initializeStep3);

it still does not work.

I was wondering if after the first server call it lost the reference to "this" or something similar to that happened where I cannot call initializeStep3 the way I am. Anyone have any ideas?

some notes:

  • I know the server webmethods are all working, I've tested them individually.
  • I'm not sure if my OO is right here.
  • I'm not sure if I'm going about AJAX right either.

Thanks for your help!

+3  A: 

You need a closure

var that = this;
PeopleServices.getFirstName(id, function (x) { 
                                    that.initializeStep3(x);
                                } 
);
epascarello