HTML and CSS Reference
In-Depth Information
At this point, the invocation code becomes:
handleNumbers(doSum, 1, 2, 3, 4);
handleNumbers(doMultiply, 1, 2, 3, 4);
With this structure in place, adding yet another operation on the array of numbers is simply a
matter of creating a function that performs the desired operation. There's no need to worry about
collecting numbers or displaying results.
Contract-based callback functions
If you strictly compare the actual effects of the two versions of the code, you should note a
difference. In the former version, where repetitive code was used you could output a message saying
something like “ SUM result is XXX .” In the more generic and callback-based solution, all you could
show to the user was the bare numeric result.
It may sound like a minor point, but it actually isn't.
The problem is that the output message needs to incorporate some information—the name of
the operation—that can be provided only by the injected function. How can you force a function like
doSum to return two values—the actual result of the operation plus the name of the operation? You
need to define a contract for the callback and actually upgrade the callback from the rank of a simple
function to the higher rank of an object.
First, you define the contract (or interface) that you expect the callback to have. The contract
defines all the information that the caller needs. In this case, the caller probably expects to find a
method to calculate a number (call it execute ) and a string to indicate the name of the operation
(call it name ). Here's how you would rewrite the handleNumbers function:
function handleNumbers(operation) {
// STEP 1: COLLECT INPUT DATA
var numbers = new Array();
for (var i = 1; i < arguments.length; i++)
numbers.push(arguments[i]);
// STEP 2: PERFORM OPERATION
var result = operation.execute(numbers);
// STEP 3: DISPLAY RESULTS
alert(operation.name + " result is " + result);
}
You now define two distinct objects— Sum and Multiplication .
var Sum = function () {
var that = {};
Search WWH ::




Custom Search