views:

88

answers:

2

I'm having a problem with using server callbacks to webmethods within an object in javascript...

function myObject() {
     this.hello = "hello";
     var id = 1;
     var name;

     this.findName = function() {
          alert(this.hello); //Displays "hello"
          myServices.getName( id, this.sayHello );
     }

     this.sayHello = function(name) {
          alert(this.hello); //Displays null <-- This is where I'm confused...
          alert(name); //Displays the name retrieved from the server
     }

     this.findName();
}

So when a new myObject is created, it finds the name, and then calls sayHello once the name has been found.

The service routine works and returns the correct name.

The issue is that after the name is returned from the server and this.sayHello is called, it doesn't seem to be in the same object (no reference to the same myObject that we were in when we were finding the name) because this.hello gives a null...

Any ideas?

+1  A: 

You have to somehow bind the scope of the 'this' object at call time so that the callback will execute within the same scope later. Currently your callback function executes in the global window scope as coded, so 'this' == Window. If you are using a framework, they usually provide some way of passing scope as part of the callback to make this easy.

You could also create a closure around the callback parameter, as explained here: http://stackoverflow.com/questions/183214/javascript-callback-scope

bmoeskau
+2  A: 

This is not a webservice issue. It's standard javascript functionality. In a callback function, the reference to "this" becomes a reference to the globally scoped "window" object. Here's how you can solve that:

function myObject() {
     this.hello = "hello";
     var id = 1;
     var name;
     var self = this; //reference to myObject
     this.findName = function() {
          alert(this.hello); /* Displays "hello" */
          myServices.getName( id, this.sayHello );
     }

     this.sayHello = function(name) {
          alert(self.hello); /* Displays "hello" instead of "undefined" */
          alert(name); /* Displays the name retrieved from the server */
     }

     this.findName();
}
Jose Basilio