[英]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.