d3.json callback function

2019-09-09 19:37发布

I'm using d3.js 3.4.13, and the docs say the callback function for d3.json(data, callback) should be of the format callback(error, responseData), however, I found that it actually sets the data to the first parameter, and the second parameter is unnecessary, so I use callback(responseData) instead. It works, but I'm confused why it doesn't work the same way I interpreted the docs to describe it. What am I missing?

1条回答
Ridiculous、
2楼-- · 2019-09-09 20:12

A quick look at the source reveals the following function:

function d3_xhr_fixCallback(callback) {
  return callback.length === 1
      ? function(error, request) { callback(error == null ? request : null); }
      : callback;
}

D3 explicitly checks the number of arguments to the callback through .length and if there's only one, puts the data in it.

So the one-argument version is a convenience version that still works as expected.

查看更多
登录 后发表回答