Skip to content

Commit 54066c7

Browse files
Improved example, added an anonymous callback and removed the while loop that was unnecessary and confusing.
Also fixed the indentation.
1 parent 144a0d0 commit 54066c7

File tree

1 file changed

+21
-21
lines changed

1 file changed

+21
-21
lines changed

function-patterns/callback.html

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -10,28 +10,23 @@
1010
Description: when you pass function A to function B as a parameter, function A is a callback function
1111
*/
1212

13+
var complexComputation = function () { /* do some complex stuff and return a node */ };
14+
1315
var findNodes = function (callback) {
14-
var i = 100000,
15-
nodes = [],
16-
found;
17-
18-
// check if callback is callable
19-
if (typeof callback !== "function") {
20-
callback = false;
21-
}
22-
23-
while (i) {
24-
i -= 1;
25-
26-
// complex logic here...
27-
28-
// now callback:
29-
if (callback) {
30-
callback(found);
31-
}
32-
33-
nodes.push(found);
16+
var nodes = [];
17+
18+
// check if callback is callable
19+
if (typeof callback !== "function") {
20+
callback = false;
3421
}
22+
23+
var node = complexComputation();
24+
25+
if (callback) {
26+
callback(node);
27+
}
28+
29+
nodes.push(node);
3530
return nodes;
3631
};
3732

@@ -41,7 +36,12 @@
4136
};
4237

4338
// find the nodes and hide them as you go
44-
findNodes(hide);
39+
var hiddenNodes = findNodes(hide);
40+
41+
// you can also use an anonymous function, like this:
42+
var blockNodes = findNodes(function (node) {
43+
node.style.display = 'block';
44+
});
4545

4646
// reference
4747
// http://www.jspatterns.com/

0 commit comments

Comments
 (0)