1

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.

Vinit Divekar
  • 774
  • 10
  • 24

1 Answers1

1

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.

Didier Aupest
  • 3,227
  • 2
  • 23
  • 35
  • Yes. That worked. @Didier Can you please explain me why did this work? – Vinit Divekar Nov 23 '17 at 00:15
  • To make it short, `this` inside `getServiceListSuccess` refers to Ajax context, and not your ViewModel, because it is the result of your ajex request. When creating your ajax request, you can specify the context, to `this`, where `this` is your current ViewModel, but it might be confusing. Referencing your current viewmodel as self all over it is quite common. – Didier Aupest Nov 23 '17 at 00:27