I’m calling ParentObject.doSomething() which inturn calls the WebService object to perform some ajax calls, and on success of the ajax call, the callback function is executed. But any parent function inside the callback function fails.
I think this has something to do with scope resolution. I am not able to find a workaround for this problem.
Is there a better architectural style to modularize the ajax services and model?
I’ve create a jsfiddle also – http://jsfiddle.net/bzKXr/2/
var ParentObject = {
doSomething: function(){
document.write("Inside doSomething <br />");
var self = this;
WebServices.firstService("some URL", self.successCallback);
},
changeData: function(data){
//Manipulate data
document.write("Inside changeData <br />");
},
successCallback: function(jsonData){
document.write("Inside successCallback <br />");
try {
//Execution fails at this point. Possibly because of scope resolution
this.changeData(jsonData);
}
catch (error) {
console.log(error);
document.write(error);
}
},
};
var WebServices = {
firstService: function(url, successCallbackHandler){
document.write("Inside firstService <br />");
//Get data using the URL
//on success call successCallback
successCallbackHandler("some data");
}
};
$(document).ready(function() {
ParentObject.doSomething();
});
Writing
self.successCallbackdoesn’t bind the function toself, you have to actually call the function asself.successCallback()to bind the context correctly.You can do that easily by wrapping the call in a closure which retains access to
self:or in ES5 you can use
.bind()which ensures that thethiscontext forsuccessCallbackis always the specified parameter: