How do you work with asp.net server callbacks in javascript objects?
I am having a problem using server callbacks for web methods inside 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 after the name is found.
The service routine runs and returns the correct name.
The problem is that after the name is returned from the server and this.sayHello is called, it looks like it is not in the same object (a reference to the same myObject we did when we found the name), because what this.hello gives null ...
Any ideas?
It's not a web surfing problem. This is standard javascript functionality. In the callback function, the reference to "this" becomes a reference to the globally scoped window object. Here's how you can solve it:
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();
}
a source to share
You need to bind the scope of the 'this' object somehow during the conversation so that the callback is executed in the same scope afterwards. Currently your callback function is executing on the global window scope as encoded, so 'this' == Window. If you're using a framework, they usually provide some way to pass the scope as part of the callback to make this easy.
You can also create a closure around the callback parameter, as described here: JavaScript Callback Scope
a source to share