d3js 图表更新在 websocket 消息上触发

d3js chart update triggered on websocket message

运行 Python 中的高速公路 websocket 服务器,并在 html 前端获取 json 更新。当消息到达并且该部分工作正常时,该值(在本例中为 "temp")显示为带有 innerHTML 的数字。

我们也得到了一个表盘图表(d3js)但是更新是由代码末尾的setInterval函数启动的,这远非理想。如何通过 websocket 更新仪表 'onmessage'?

<script type="text/javascript">

//---the websocket part--
var sock = null;
var displaynumber = null;
var tempdata = null;

window.onload = function () {
  var wsuri;
  displaynumber = document.getElementById('disp');

  if (window.location.protocol === "file:") {
    wsuri = "ws://...:9000";
  } else {
    wsuri = "ws://" + window.location.hostname + ":9000";
  }

  //set up a new websocket
  if ("WebSocket" in window) {
      sock = new WebSocket(wsuri);
  } else if ("MozWebSocket" in window) {
      sock = new MozWebSocket(wsuri);
  } else {
      disp("Browser does not support WebSocket!");
               window.location = "http://autobahn.ws/unsupportedbrowser";
  }

  if (sock) {
    //sock.onopen = function() {};

    sock.onclose = function(e) {
      sock = null;
    };

    sock.onmessage = function(e) {
      // e.data will be sent as a string and need to be converted to object
      var jsondata = JSON.parse(e.data);
      tempdata = jsondata.temp;
      disp(tempdata + " C");
    };
  }

  function disp(m) {
    displaynumber.innerHTML = m;
  }


  //----This is the dial chart part

  dialChart();

  function dialChart() {
    var powerGauge = gauge('#power-gauge', {
      size: 300,
      clipWidth: 300,
      clipHeight: 300,
      ringWidth: 60,
      minValue: 0,
      maxValue: 100,
      transitionMs: 1000,
    });

    powerGauge.render();

    function updateReadings() {
      powerGauge.update(tempdata);
    }

    updateReadings();
    setInterval(function() {
      updateReadings();
    }, 2 * 1000);
  }
}

</script>

dialChart的定义末尾添加return powerGauge。然后当你调用 dialChart(); 时,将结果保存到一个变量中。然后,不是在套接字回调中写入 tempdata,而是调用 powerGaugeVariable.update(jsondata.temp).