开发者

jQuery problem with (a)synchronous method calls

I have an strange behavior, which looks lika an problem with (a)synchronous method calls?!? I'm not sure! An function receives data using getJSON, post process those data, add them to an table, which is sortable by the table-sorter plugin (http://tablesorter.com/).

Here some parts of the code. A function receives data by getJSON:

jQuery.getJSON(url,{},function(data)
              {
             success:{ ....

in the success block, the data will be processed in an for-each loop. during that f开发者_高级运维or-each loop, every JSON element will be manipulated (doSomething()) an added to an HTML table:

success:{ [some-code]
          $.each (data.words, function (i,n) 
                              {result=doSomething(n);
                               obj=jQuery('#Template').clone().appendTo('#table');
                               obj.html(result);
                              }

finaly, after that for-each i have to update the Table-sorter -extension and start an new sorting:

         jQuery("#table").trigger("update");
         $("#table").trigger("sorton",[[[1,1]]]);
}; //end of "success

This code is simplified. The Problem is, that $("#table").trigger("sorton",[[[1,1]]]); only works correctly, if i start this function delayed setTimeout('$("#trends").trigger("sorton",[[[1,1]]]);',20);.

I think, that the output obj.html(result); will be asynchronous. So if i start the sorter-function without setTimeout, the sorter-function founds no data at runtime.

Is there a way to make that success block linear?

Thank you, for any kind of help!!


If you look at the source for the tablesorter, the update event has a setTimeout in it, which is most likely what is affecting your call to sort the table.

$this.bind("update", function () {
    var me = this;
    setTimeout(function () {
    // rebuild parsers.
        me.config.parsers = buildParserCache(
        me, $headers);
        // rebuild the cache map
        cache = buildCache(me);
    }, 1);

A complete hack would be to add your sorting to the end of that block of code. A more elegant solution I'm not sure I can provide, but I wanted to share that finding with you.


I think you more or less solved your own problem. Put all of your success: callback code in a function and specify that function in the success attribute. The getJSON() call is asynchronous, so when it completes there needs to be a function existing for it to call.

By that I mean, do this:

success: doSuccess();

and not this:

success: function() {}

Alternatively, you can make the call synchronous if you want to, see this: Is there a version of $getJSON that doesn't use a call back?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜