JQuery - Using post/ajax results in multiple functions
In a nutshell: Using jquery I want to get some xml output and use it with a custom grid plugin. My problem is in efficiently getting the data I need into the plugin.
That plugin needs to get the count of returned nodes and the rows themselves. Currently I make 2 separate calls to get the xml, one gets it and counts the nodes and returns that number to the plugin, one gets it again sorts the data itself and passes it to the plugin for formatting and display.
So the plugin setup lo开发者_高级运维oks something like this:
$("someID").thePlugin({count:countFunction, rows:loadRowsFunction});
where countFunction gets the xml file and counts the nodes and loadRowsFunction ALSO gets the xml file and loads the data. I want to get the xml file once. What is the best way to go about this?
The logical choice would be to separate the functionality. This goes with the "DRY" (Don't Repeat Yourself) principle of coding.
Remove the XML fetching portion of your count function and loadRows function, and put it into it's own function, say, xmlFetch().
Now, make xmlFetch() have a caching mechanism. By default, it fetches the content the first time it is called, and stores it in memory. If another request comes to xmlFetch(), it just returns the already fetched data. You can make it optional to override the caching mechanism if you want to do a re-fetch of the data.
Now, your count function and loadRows function can both call on xmlFetch() and it will only ever fetch the results once, unless specifically told to re-fetch.
精彩评论