2013-07-03 70 views
1

我正在繪製與RickshawJS不同的數據。但是當用戶點擊#search按鈕時,我需要一種更新圖表的方法。現在它只是在舊的圖表下面創建一個新的圖表,而這非常麻煩。將數據添加到空人力車圖表

用戶進入頁面並輸入一些詳細信息,然後單擊該按鈕進行繪製。所以理想情況下,我想從一張未顯示的空白圖表開始,但我無法弄清楚如何從圖表和座標軸中刪除數據,然後進行更新。

我可以在圖表和座標軸上打電話$('#chart svg').remove();,但看起來很亂。

$('#search').click(function(event){ 
    event.preventDefault(); 

    var data = utils.malletData(); 
    var graph = new Rickshaw.Graph({ 
      element: document.querySelector("#chart"), 
      width: 800, 
      height: 250, 
      series: [ { 
        name: data['name'], 
        color: 'steelblue', 
        data: data['series'] 
      } ] 
    }); 
    graph.render(); 

    var hoverDetail = new Rickshaw.Graph.HoverDetail({ 
     graph: graph, 
     xFormatter: function(x) { 
      var date = new Date(x).getTime(); 
      return moment(x).format('MMMM Do YYYY, h:mm:ss a'); 
     }, 
     yFormatter: function(y) { return Math.floor(y) + " users" } 
    }); 

    var xAxis = new Rickshaw.Graph.Axis.X({ 
     graph: graph, 
     orientation: 'bottom', 
     element: document.getElementById('x_axis'), 
     tickFormat: function(x) { return moment(x).fromNow(); }, 
     ticks: 7, 
     tickSize: 1, 
    }); 
    xAxis.render(); 

    var ticksTreatment = 'glow'; 
    var yAxis = new Rickshaw.Graph.Axis.Y({ 
     graph: graph, 
     orientation: 'left', 
     tickFormat: Rickshaw.Fixtures.Number.formatKMBT, 
     ticksTreatment: ticksTreatment, 
     element: document.getElementById('y_axis'), 
    }); 
    yAxis.render(); 
}); 

回答

5

有沒有官方的方式來這樣做。但是,您可以利用javascript中的數組通過引用傳遞並更新圖形的事實。

看一看這個demo on fiddle

var data = [ 
     { 
      data: [ { x: 0, y: 120 }, { x: 1, y: 890 }, { x: 2, y: 38 }, { x: 3, y: 70 }, { x: 4, y: 32 } ], 
      color: "#c05020" 
     }, { 
      data: [ { x: 0, y: 80 }, { x: 1, y: 200 }, { x: 2, y: 100 }, { x: 3, y: 520 }, { x: 4, y: 133 } ], 
      color: "#30c020" 
     } 
]; 


var graph = new Rickshaw.Graph({ 
    element: document.getElementById("chart"), 
    renderer: 'line', 
    height: 300, 
    width: 800, 
    series: data 
}); 

var y_ticks = new Rickshaw.Graph.Axis.Y({ 
    graph: graph, 
    orientation: 'left', 
    tickFormat: Rickshaw.Fixtures.Number.formatKMBT, 
    element: document.getElementById('y_axis'), 
}); 

graph.render(); 


$('button#add').click(function() { 
    data.push({ 
      data: [ { x: 0, y: 200 }, { x: 1, y: 390 }, { x: 2, y: 1000 }, { x: 3, y: 200 }, { x: 4, y: 230 } ], 
      color: "#6060c0" 
    }); 
    graph.update(); 
});