Reputation: 4574
NOTE: question edited for clarity 4/5/2014
I am making a method call using JSON RPC that requests data from the server. When that data comes back it fires a callback function. JSON RPC callback functions are automatically supplied output and exception arguments from the server. Currently I have a single function that both makes the RPC request and processes and displays the data. I want to separate my request concerns from my display concerns so that the code is more reusable. In order to do this I need to pass the resultRegion id argument to the callback function as well.
Here's an example of the currently functional but conjoined code:
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);
}
EDIT: Here's the working code that I landed on after using David SkyMesh's answer.
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);
};
}
Upvotes: 0
Views: 588
Reputation: 5171
Let's start with the obvious closure-based approach:
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);
}
Upvotes: 1