Call parent object method inside function with callback handler

Viewed 8883

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();

});
​
5 Answers
Related