Working with the this Function ASP.NET

XML HTTP callbacks are not executed on the same context where they are called.For example, if you are making a web method call from a JavaScript class:

function SampleClass( )

What happens when you call the call method? Do you get "1" on the debug console? No, you get null on the debug console because this is no longer the instance of the class, which is a common mistake everyone makes,especially because it is not yet
documented in Ajax documentations.

We know whenever Java Script events are raised that this refers to the HTML element that produces the event.So, if you run this code:

function SampleClass( )

and if you click the button, you see "ButtonID" instead of "1" because the button is making the call. So,the call is made within the button object’s context and thus this refers to the button object, not the instance of the class.

Similarly,when XML HTTP raises the event on ready state changed and ASP.NET AJAX traps and fires the call back,the code execution is still on the XML HTTP’s context.It’s the XML HTTP object that raises the event. As a result, this refers to the XML HTTP object, not your own class where the callback is declared.

To make the callback fire in the context of the class’s instance so that this refers to the instance of the class, you need to make the following change:

function SampleClass( )

Here, the Function.createDelegate is used to create a delegate that calls the given function under the this context when passed as the first parameter.Function.createDelegate is defined in Ajax runtime as:

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

ASP.NET Topics