公开函数和 return 对象

Expose function and return object

我正在尝试创建一个 ajaxHelper 模块,它应该能够公开一些函数,并且在调用它们时,应该 return 一个具有从 AJAX 调用,或与该 AJAX 调用相关的错误。

以下是我的想法:

define("helpers-ajaxDataRetriever", ["jquery"], function ($) {

    var helper = {};

    helper.getIndexData = function() {
        fnIndexData();
        return helper;
    }

    var fnIndexData = function () {
        $.ajax({
            url: nwatchBaseUrl + '/api/HomeApi/NodeSummary'
        }).success(function (returnedData) {
            helper.success = true;
            helper.data = returnedData;
        }).fail(function (jqXHR, textStatus) {
            helper.success = false;
            helper.error.jqXHR = jqXHR;
            helper.error.textStatus = textStatus;
        });
    }

});

然后我希望导入此 ajaxHelper 的其他模块能够调用该函数(例如 getIndexData),该函数最终将填充帮助程序对象,然后能够引用各种属性,例如布尔值 success 、数据或错误对象。

我该怎么做?

为了按照您期望的方式工作,该模块必须 return 您希望向外界公开的属性(以便其他模块使用)。

并且由于 ajax 是异步的,因此您最好使用回调而不是直接访问变量来处理此类情况。因为您不知道 ajax 调用何时会成功完成并且 return 您的数据。

define("helpers-ajaxDataRetriever", ["jquery"], function($) {

  var helper = {};
  // you will pass in the options
  // which will contains the success and error 
  // callbacks, along with additional props
  // that you wanna pass in and use
  helper.getIndexData = function(options) {
    fnIndexData(options);
  }

  var fnIndexData = function(options) {
    $.ajax({
      url: options.nwatchBaseUrl + '/api/HomeApi/NodeSummary'
    }).success(function(returnedData) {
          options.success && options.success.apply(null, arguments);
    }).fail(function(jqXHR, textStatus) {
       options.error && options.error.apply(null, arguments);
    });
  }

  // You return the object, which are the public methods
  // or properties which you wanna expose when this module is used
  return {
    getIndexData: getIndexData
  }
});

// This is when you wanna use the above exposed function
// in any module
define("use-ajax", ["helpers-ajaxDataRetriever"], function(customAjax) {

    var options = {
        success: function(data) {
            console.log('success');
            // use the data
        }, error: function(jqXHR, textStatus) {
             console.log('failure');
             // you will have access to the 
             // arguments of the error function here
        },
        nwatchBaseUrl: 'https://google.com/'
    }

    customAjax.getIndexData(options);
});

并且由于我们只想在上面的示例中公开 getIndexData,我们可以完全摆脱 helper 命名空间而只 return 函数定义。

你也可以通过promise

的概念实现保存