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);
      }
    }
  });
}

関数を使用して、渡される成功ハンドラーを利用します。たとえば、そのような成功ハンドラーの 1 つが ですclientRelationshipHandler

ハンドラーが次のように定義されている場合

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

次にwindow["clientRelationshipHandler"]、関数を返します。

ただし、次のように変更すると

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

両方

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

未定義を返すため、一般的な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 に答える