无法在Ajax的成功回调函数中访问视图模型的可观察和函数 - Knockout

时间:2017-11-22 23:40:40

标签: ajax knockout.js knockout-3.0

以下是我创建的小提琴,用于演示我面临的问题: 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();
};

我正在尝试拨打' testFunction' Ajax调用的成功回调函数(getServiceListSuccess)中的视图模型。

当我尝试调用该函数时,我收到错误

  

' this.testFunction不是函数'

如何访问ajax回调中的视图模型observables和函数?

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

以下是您的问题的快速解决方法: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();
};

当你调用它时,在你的功能中,你的范围已经改变了。因此,您需要保留对viewmodel的引用。

相关问题