簡體   English   中英

JavaScript范圍:在事件處理程序中訪問變量?

[英]JavaScript scope: access variable inside event handler?

我有以下代碼。 它在D3中繪制堆疊圖形,然后允許用戶通過從下拉列表中選擇一個選項來過濾顯示的行。

但是,我的范圍有問題。 當我使用下拉列表時,控制台語句顯示series 1已正確更新。 但是,mousemove代碼中的series 2尚未更新。

我猜這是因為它已經綁定,並且在變量更新時沒有更新。 如何訪問更新的變量?

 d3.csv("/data/test.csv", function(error, data) {

  function updateGraph(label) {

    // Filter the data. 
    var series = data.filter(function(d, i) {
      return d.Type == label;
    });
    console.log('series 1', series); // This updates correctly. 

    // Draw the paths. 
    var items = svg.selectAll("path").data(newSeries);
    items.enter().append('path').attr("d", function(d) {
      return area(d.data);
    }).on("mousemove", function(d, i) {
      console.log('series 2', series); // This is out of date. 
    });
  }

  // Draw the initial graph. 
  updateGraph('initial');
  // When the user changes the drop-down, redraw the graph. 
  d3.select("#chooseoption").on("change", function(val) {
    updateGraph(this.options[this.selectedIndex].value);
  });

});

如果您希望有一個多個事件處理程序可以訪問或修改的單個series變量,那么您需要在所有想要參與的事件處理程序的范圍內定義該變量,以便它們共享對同一變量的訪問權限而不是多個變量的副本存在於多個閉包中。

在這種情況下,您可以這樣做:

d3.csv("/data/test.csv", function(error, data) {

  // define series variable where multiple event handlers can share it
  var series;
  function updateGraph(label) {

    // Filter the data. 
    series = data.filter(function(d, i) {
      return d.Type == label;
    });
    console.log('series 1', series); // This updates correctly. 

    // Draw the paths. 
    var items = svg.selectAll("path").data(newSeries);
    items.enter().append('path').attr("d", function(d) {
      return area(d.data);
    }).on("mousemove", function(d, i) {
      console.log('series 2', series); // This is out of date. 
    });
  }

  // Draw the initial graph. 
  updateGraph('initial');
  // When the user changes the drop-down, redraw the graph. 
  d3.select("#chooseoption").on("change", function(val) {
    updateGraph(this.options[this.selectedIndex].value);
  });

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM