Search code examples
ajaxknockout.jsknockout-3.0

Cannot access view model's observables and functions inside Ajax's success call back function- Knockout


Following is the fiddle I have created to demonstrate the issue I am facing: https://jsfiddle.net/divekarvinit/uyu87427/2/

this.getServiceListSuccess = function(response) {
    // The following line gives me error as 'this.testFunction is not a 
    //function'
    this.testFunction();
};

I am trying call the 'testFunction' of the view model inside the success callback function (getServiceListSuccess) of an Ajax call.

When I try to call the function, I get error as

'this.testFunction is not a function'

How can I access view models observables and functions in the ajax callback?

Any help will be appreciated.


Solution

  • Here is a quick fix on your issue: https://jsfiddle.net/uyu87427/3/

    var self = this;
    this.getServiceListSuccess = function(response) {
        // The following line gives me error as 'this.testFunction is not a 
        //function'
        self.testFunction();
    };
    

    when you are calling this, inside your function, your scope has changed. So, you need to keep a reference to your viewmodel.