开发者

jquery - update jquery.sparkline after async data fetch

Background

i'm using jquery.sparkline to produce Pie Charts. The data for the Pie Chart is contained in an array.

When the page is first loaded a web-service is called (using .ajax) to get the data, the callback specified there takes the received data and updates the array associated with the pie chart.

That same update process is invoked when a dropdown on the screen changes value.

Situation

If I set the .ajax call to asynch=false this all works fine.

If I set the .ajax call to asynch=true the results shown in the pie are always 'one refresh behind'. By this I mean there's no pie initially and then when the dropdown is changed the pie is rendered as it should have been initially.

Code

$.ajax({
    type: "GET",
    contentType: "application/json; charset=utf-8",
    url: requestURL,
    async:   true ,
    success: function (data) { successCallback(data); },
    error: function (data) { failureCallback(data); }
});

Help? Anyone out there recognise this problem ?

Options I've been looking at variations on the Observer pattern to monitor a change to the array and the (not sure how) persuade the jquery.sparkline object to redraw itself but this seems crazy and I'm sure I must be overlooking something much more straightforward.



Thanks to Gareth and his sample code I was able to see what I was doing wrong (which wasn't anything to do with jquery.sparkline.

I had some functions like this :

function RefreshPieChart(){
    //First call managePieDataFetch() 
    //to kick off the web-service request

    managePieDataFetch();

    //now reinitialise the jquery.sparkline
    //pie charts on the basis that the 
    //array variable initialised in 
    //pieDataFetchCallBack() has the newest 
    //dat开发者_运维知识库a in it.
    //
    //.... It hasn't !
}
function managePieDataFetch(){
    //invoke the .ajax call and 
    //provide function pieDataFetchCallBack() as 
    //a call back function
}
function pieDataFetchCallBack(){
    //post process the data
    //returned from a successful
    //ajax call. Place the results
    //into an array variable at
    //script scope
}


I'd need to see a more complete example to determine where the problem is, but using async: true works fine for me.

Here's a link to a very simple working example: http://omnipotent.net/jquery.sparkline/ajaxtest.html

The source for the ajax side is here: http://omnipotent.net/jquery.sparkline/ajax.phps

If your chart is hidden (ie. display: none) at the time .sparkline() is actually called then you may need to call $.sparkline_display_visible() at the point the chart is made visible to force it to be rendered at that point.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜