繁体   English   中英

javascript / D3基础:如果异步调用,为什么代码不在json请求之外?

[英]javascript/D3 basics: If asynchronous call, why is code outside of json request?

在d3 javascript中读取变量作用域后,我认为一般来说,您应该将所有函数放在d3.json() {}请求中。

我正在使用来自http://techslides.com/demos/d3/us-zoom-county.html的一些地图缩放代码,并试图找出为什么clicked(d)函数不在d3.json请求中。

此外,为什么代码无法与d3.json请求中的clicked(d)函数d3.json

var width = 960,
    height = 500,
    centered;

var projection = d3.geo.albersUsa()
    .scale(1070)
    .translate([width / 2, height / 2]);

var path = d3.geo.path()
    .projection(projection);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

svg.append("rect")
    .attr("class", "background")
    .attr("width", width)
    .attr("height", height)
    .on("click", clicked);

var g = svg.append("g");

d3.json("data/us.json", function(error, us) {


 g.append("g")
      .attr("id", "counties")
    .selectAll("path")
      .data(topojson.feature(us, us.objects.counties).features)
    .enter().append("path")
  .attr("d", path)
  .attr("class", "county-boundary")
      .on("click", countyclicked);

  g.append("g")
      .attr("id", "states")
    .selectAll("path")
      .data(topojson.feature(us, us.objects.states).features)
    .enter().append("path")
  .attr("d", path)
  .attr("class", "state")
      .on("click", clicked);


  g.append("path")
      .datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
      .attr("id", "state-borders")
      .attr("d", path);
});


function clicked(d) {
  var x, y, k;

  if (d && centered !== d) {
    var centroid = path.centroid(d);
    x = centroid[0];
    y = centroid[1];
    k = 4;
    centered = d;
  } else {
    x = width / 2;
    y = height / 2;
    k = 1;
    centered = null;
  }

  g.selectAll("path")
      .classed("active", centered && function(d) { return d === centered; });

  g.transition()
      .duration(750)
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")")
      .style("stroke-width", 1.5 / k + "px");
}

function countyclicked(d) {
  alert(d.id);
}

我试图弄清楚为什么clicked(d)函数不在d3.json请求之外。

定义函数的地方几乎无关紧要,只需要从引用位置就可以访问它。 clicked是内部接近d3.json回调,所以这是很好。

函数的位置仅在假定为闭包时才重要,即需要访问未作为参数传递的值。 例如,如果clicked需要直接访问us ,则必须在回调中定义它。
但是,这里不是这种情况, clicked通过其参数获取所需的所有数据。

然而,这里重要的是接收到数据 ,功能才会被调用,因为它必将为回调内部的事件处理程序( .on("click", clicked) )基于所接收到的数据。

为什么代码不能与d3.json请求中的clicked(d)函数d3.json

我看不出有什么理由。

这是因为该函数还在回调之外绑定到此处的容器:

svg.append("rect")
  .attr("class", "background")
  .attr("width", width)
  .attr("height", height)
  .on("click", clicked);

如果您在回调内部移动,则该代码外部将无法再访问它。

请注意, clicked本身通过检查参数d是否设置来检查数据是否可用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM