向JSON RPC回调函数添加参数

时间:2014-04-01 22:18:10

标签: javascript callback json-rpc

注意:为了清晰起见而编辑的问题4/5/2014

我正在使用JSON RPC进行方法调用,该请求来自服务器的数据。当该数据返回时,它会触发回调函数。 JSON RPC回调函数是从服务器自动提供的输出和异常参数。目前我有一个函数,它既可以生成RPC请求,也可以处理和显示数据。我想将我的请求问题与显示问题分开,以便代码更可重用。为此,我需要将resultRegion id参数传递给回调函数。

以下是当前功能性但联合代码的示例:

function customerTable(inputField, resultRegion) {
  var displayAccountTable = function(accounts, exception) {
    if(exception) {
      alert(exception.msg);
    }
    else {
      var headings = ["Account ID", "First Name", "Last Name", "Balance"];
      var rows = new Array();
      for(var i=0; i<accounts.length; i++) {
        var account = accounts[i];
        rows[i] = [account.accountID, account.firstName, account.lastName, account.prettyAccountBalance];
      }
      var table = getTable(headings, rows);
      htmlInsert(resultRegion, table);
    }
  };
  var inputs = commaStringToArray(getRawValue(inputField));
  rpcClient.rpcTester.getAccounts(displayAccountTable, inputs);
}
编辑:这是我在使用David SkyMesh的答案后登陆的工作代码。

function customerTable(inputField, resultRegion) {
  var inputs = commaStringToArray(getRawValue(inputField));
  rpcClient.rpcTester.getAccounts(displayAccountTable(resultRegion), inputs);
}

function displayAccountTable(resultRegion) {
  return function (accounts, exception) {
    if(exception) { return alert(exception.msg); }
    var headings = ["Account ID", "First Name", "Last Name", "Balance"];
    var account, rows = [];
    for(var i=0; i<accounts.length; i++) {
      account = accounts[i];
      rows[i] = [account.accountID, account.firstName, account.lastName, account.prettyAccountBalance];
    }
    var table = getTable(headings, rows);
    htmlInsert(resultRegion, table);
  };
}

1 个答案:

答案 0 :(得分:1)

让我们从明显的基于闭包的方法开始:

function mk_displayAccountTable(inputField, resultRegion) {
  return function (accounts, exception) {
    if (exeption) return alert(exception.msg);
    var headings = ["Account ID", "First Name", "Last Name", "Balance"];
    var i, account, rows = [];
    for(i=0; i<accounts.length; i++) {
      account = accounts[i];
      rows.push([account.accountID, account.firstName, 
                account.lastName, account.prettyAccountBalance]);
    }
    var table = getTable(headings, rows);
    htmlInsert(resultRegion, table);
  };
}

function customerTable(inputField, resultRegion) {
  var inputs = commaStringToArray(getRawValue(inputField));
  rpcClient.rpcTester.getAccounts(
    mk_displayAccountTable(inputField, resultRegion), 
    inputs);
}