0

我有一个 webapp 已被重构为使用格式中的单个全局变量

app.module.function
app.module.submodule.function

我想重构我现有的泛型

function getData(id, type, url, successHandler, rel) {

  var func = window[successHandler]

  $.ajax({
    type : "POST",
    url : url,
    data : {"search" : id, "type" : type, "rel" : rel},
    dataType: "json",
    success : function(data) {
      if (func && typeof func === "function") {
        func(data, id, 0);
      }
    }
  });
}

函数来利用传入的成功处理程序。例如,一个这样的成功处理程序是clientRelationshipHandler.

如果处理程序定义为

function clientRelationshipHandler(results, id, type) { .. }

然后window["clientRelationshipHandler"]返回一个函数。

但是,如果我将其更改为

app.module.submodule.clientRelationshipHandler = function(results, id, type { .. }

两个都

window["clientRelationshipHandler"]
window["app;.module.submodule.clientRelationshipHandler"]

返回 undefined 并因此破坏通用getData功能。在使用绑定到特定对象的函数时,如何为 Ajax 查询实现通用成功处理程序?

4

1 回答 1

2

我会要求用户将函数引用传递给getData,而不是字符串:

function getData(id, type, url, successHandler, rel) { 
  $.ajax({
    type : "POST",
    url : url,
    data : {"search" : id, "type" : type, "rel" : rel},
    dataType: "json",
    success : function(data) {
      if (successHandler && typeof successHandler === "function") {
        successHandler(data, id, 0);
      }
    }
  });
}

// called as
getData(id, type, url, app.module.submodule.clientRelationshipHandler, rel);

然后您的函数不必关心回调的存储位置,这使得它更易于重用(这就是回调应该如何工作)。

如果你想保留this在回调中,要么接受一个额外的参数,thisObj然后使用successHandler.call(thisObj, data, id, 0)或让用户自己处理(例如,通过使用.bind或提供一个匿名函数)。


一个更好的解决方案(IMO)是使用promises

function getData(id, type, url, rel) {
  return $.ajax({ // return the promise that `$.ajax` returns
    type : "POST",
    url : url,
    data : {"search" : id, "type" : type, "rel" : rel},
    dataType: "json"
  });
}

然后称为

getData(id, type, url, rel).then(function(result) {
    app.module.submodule.clientRelationshipHandler(result, id, 0);
});

这将您的代码与回调管理完全分离,调用代码可以以任何它想要的方式处理响应。

于 2013-09-16T16:05:42.660 回答