没有调用jquery异步函数

时间:2016-05-13 10:39:31

标签: javascript jquery sqlite cordova backbone.js

我正在使用cordova创建我的移动应用程序。当我从sqlite数据库获取数据时需要一些时间,这就是我使用延迟jquery的原因。但我无法从$ .when deferred jquery调用函数。我很困惑。请帮帮我。

callPaymentApi: function (e) {
    var loginDeferred = $.Deferred();
    var loginList = [];
    var dbLogin = new DBLogin();
    dbLogin.getLoginDetail(function (data) {
        loginList = data;
        loginDeferred.resolve();
    });
    $.when(loginDeferred).then(function success() {
        var email_id = loginList[0].email_id;
        var token_id = loginList[0].token_id;
        currTime = MyApp.getRequestTime();

        var data = {};
        data.request_time = currTime;
        data.token_id = token_id;
        data.email_id = email_id;
        console.log("data :::::::::: " + JSON.stringify(data));

        var net = MyApp.checkNetworkConnection();
        if (net == true) {
            $.blockUI();
            var urlRoot = String.baseURL + 'fetchdata';
            var loginModel = new Model();
            loginModel.urlRoot = urlRoot;
            loginModel.save(data, {
                success: function (response) {
                    $.unblockUI();
                    console.log("success ....." + JSON.stringify(response));
                    this.successHandler(response);
                },
                error: function (response) {
                    $.unblockUI();
                    console.log("error ....." + JSON.stringify(response));
                    this.errorHandler(response);
                }
            });
        } else {
            navigator.notification.alert(l('%alert.internet.connection'), null, null, l('%common.OK'));
        }
    });
},
successHandler: function (response) { //Success handler 
    $.unblockUI();
    alert("success");
},
errorHandler: function (response) { //Success handler 
    $.unblockUI();
    alert("success");
}

我在日志中获得了数据。 REST API也运行良好并获得成功响应。但是当我从成功和错误中调用函数时,它就不起作用了。我无法将这些功能称为“successHandler”& “的ErrorHandler”。

提前致谢!

1 个答案:

答案 0 :(得分:0)

回调中的上下文将有所不同。您需要保存对当前上下文的引用,例如:

callPaymentApi: function(e) {
    var that = this;
    ...
    $.when(loginDeferred).then(function success() {
      ...
      loginModel.save(data, {
        success: function(response) {
          ...
          that.successHandler(response);
        },
        error: function(response) {
          ...
          that.errorHandler(response);
        }
      });
    });
  },
  successHandler: function(response) { //Success handler 
    $.unblockUI();
    alert("success");
  },
  errorHandler: function(response) { //Success handler 
    $.unblockUI();
    alert("success");
  }