Saturday, August 27, 2011

Javascript - Executing callback methods with prototype methods and JQuery Ajax requests

If you have something like this:
var data = {};

var test = MyClass();

test.CommonMethod(ajaxSuccess,data);



function ajaxSuccess(data){

alert("ajax done!");

}

And this doesn't work because most probably your class is something like this:
function MyClass()

{

this.message = null;

this.callbackFunction = null;

}



MyClass.prototype.CommonMethod = function(callback, data) {

this.callbackFunction = callback;

$.ajax({

url: "http://mydomain.com/executetest/",

dataType: 'jsonp',

data: data,

success: CommonSuccessMethod

});

}



MyClass.prototype.CommonSuccessMethod = function(data) {

this.callbackFunction(data);

}



The reason why this doesn't work, the "this" on the "CommonSuccessMethod" is out of scope (from ajax request). To make it work, you must include the reference of the object executing the ajax request.

Here's a modified version of the class:

function MyClass()

{

this.message = null;

this.callbackFunction = null;

}



MyClass.prototype.CommonMethod = function(callback, data) {

this.callbackFunction = callback;

$.ajax({

url: "http://mydomain.com/executetest/",

dataType: 'jsonp',

data: data,

success: CommonSuccessMethod,

classInstance: this

});

}



MyClass.prototype.CommonSuccessMethod = function(data) {

this.classInstance.callbackFunction(data);

}




Now, on the method "CommonSuccessMethod". you can access the executing class thru "this.classInstance" and this will execute your "ajaxSuccess" method.

No comments:

Post a Comment