javascript - Function chaining -
i struggling understand how javascript code work. learning js, , not exposed dynamic, functional language before. so, visualize function calls in bit procedural, hierarchical order. d3.js, 1 can draw svg elements explained here
var dataset = [ 5, 10, 15, 20, 25 ]; d3.select("body").selectall("p") .data(dataset) .enter() .append("p") .text("new paragraph!"); let’s change last line:
.text(function(d) { return d; }); check out new code on demo page.
whoa! used our data populate contents of each paragraph, magic of data() method. see, when chaining methods together, anytime after call data(), can create anonymous function accepts d input. magical data() method ensures d set corresponding value in original data set, given current element @ hand.
this magic, mentioned above fail understand. "d" not global variable, if change (c) name, still works. so, data method may setting value anonymous fn.
but, typically(with limited reading) chaining possible because current function returns object, on next method can invoked. in above case, how data method knows whether text ("new paragraph!") passed user, otherwise pass data anonymous fn. doubt is, text method down line , data() executed. how data passed anonymous function?
thanks.
digging d3.js internals shows following result text function:
d3_selectionprototype.text = function(value) { return arguments.length < 1 ? this.node().textcontent : this.each(typeof value === "function" ? function() { var v = value.apply(this, arguments); this.textcontent = v == null ? "" : v; } : value == null ? function() { this.textcontent = ""; } : function() { this.textcontent = value; }); }; in case supplied argument function, following code gets executed:
this.each(function() { var v = value.apply(this, arguments); // executing function provided this.textcontent = v == null ? "" : v; }); function each declared as:
d3_selectionprototype.each = function(callback) { (var j = -1, m = this.length; ++j < m;) { (var group = this[j], = -1, n = group.length; ++i < n;) { var node = group[i]; if (node) callback.call(node, node.__data__, i, j); // line interested in } } return this; }; so on each invocation supplies element this. and, getting down it, this populated data function invocation.
Comments
Post a Comment