jqplot動態填充資料,網上以下三種方法:
大家在使用jqPlot動態更新圖表時,也許會碰到過在IE中出現記憶體溢出的問題,下面我們來看看集中動態更新jqPlot圖表的方式:
方式一:通過重建圖表實現動態顯示。
Javascript代碼
-
var series = [{'test'}];
-
-
var axes = {
-
xaxis : {
-
renderer : $.jqplot.CategoryAxisRenderer,
-
ticks : []
-
},
-
yaxis : {
-
min : 0,
-
max : 10,
-
tickInterval : 2
-
}
-
};
-
-
var plotConfig = createBarChartOptions(axes, series);
-
-
resizeGlobalMonitorChartContainer(containerId);
-
-
var plot = $.jqplot(g_channelDivId, chartData, plotConfig);
實際上我們通過重複的建立圖表,確實可以實現動態更新,不過在IE下,我們會發現記憶體增長很厲害,起初,通過嘗試在重新建立圖表時,提前銷毀舊的圖表來釋放記憶體:
Javascript代碼
-
/**
-
* 將plot圖表從容器中銷毀。
-
*
-
* @param containerId
-
* 容器ID。
-
* @param plot
-
* 在容器中的圖表。
-
*/
-
function releasePlotChart(containerId, plot) {
-
if (plot) {
-
plot.destroy();
-
-
var elementId = '#' + containerId;
-
$(elementId).unbind(); // for iexplorer
-
$(elementId).empty();
-
-
plot = null;
-
}
-
}
當我們觀察記憶體變化的時候,會發現銷毀圖表時記憶體減少了,但是重建之後,記憶體會比原來多出一些,一定時間以後,記憶體就會不斷的增加,最後導致記憶體溢出。
方式二:通過動態資料載入,重繪實現。
Javascript代碼
-
/**
-
* 重繪plot圖表。
-
*
-
* @param containerId
-
* 容器ID。
-
* @param chartData
-
* 圖表資料。
-
* @param plotConfig
-
* 圖表配置資訊。
-
* @returns 返回重繪後的圖表對象。
-
*/
-
function replotChart(plot, chartData) {
-
setChartDataToPlot(plot, chartData);
-
-
plot.replot({
-
resetAxes : true
-
});
-
-
return plot;
-
}
-
-
/**
-
* 將最新的資料設定到plot圖表中。
-
*
-
* @param plot
-
* @param chartData
-
*/
-
function setChartDataToPlot(plot, chartData) {
-
for ( var i = 0; i < plot.series.length; i++) {
-
for ( var j = 0; j < plot.series[i].data.length; j++) {
-
try {
-
plot.series[i].data[j][1] = chartData[i][j];
-
} catch (e) {
-
}
-
}
-
}
-
}
通過運用這種方式,再次觀察記憶體變化,會發現記憶體溢出問題已經不存在了。
從中我們發現,只要重建Plot圖表,記憶體就會出現遞增的現象,因此,當我們需要切換圖表的時候,最好將原來的圖表隱藏起來,當再次需要顯示的時候,再恢複顯示,從而避免重複建立圖表,從而導致記憶體溢出。
目前我使用的是第三種方法,不知道在之後使用過程中會不會出現一些bug,有待觀察。
http://stackoverflow.com/questions/5178197/how-to-refresh-jqplot-bar-chart-without-redrawing-the-chart
這個網站中使用的是第二種方法,可以做為參考,有些情況圖表不僅僅需要重新讀資料,還需要重新畫,估計就得用這種方法了?還沒有仔細研究。有時間會做實驗。