QueryResults.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. define("dojo/store/util/QueryResults", ["../../_base/array", "../../_base/lang", "../../_base/Deferred"
  2. ], function(array, lang, Deferred) {
  3. // module:
  4. // dojo/store/util/QueryResults
  5. // summary:
  6. // The module defines a query results wrapper
  7. var util = lang.getObject("dojo.store.util", true);
  8. util.QueryResults = function(results){
  9. // summary:
  10. // A function that wraps the results of a store query with additional
  11. // methods.
  12. //
  13. // description:
  14. // QueryResults is a basic wrapper that allows for array-like iteration
  15. // over any kind of returned data from a query. While the simplest store
  16. // will return a plain array of data, other stores may return deferreds or
  17. // promises; this wrapper makes sure that *all* results can be treated
  18. // the same.
  19. //
  20. // Additional methods include `forEach`, `filter` and `map`.
  21. //
  22. // returns: Object
  23. // An array-like object that can be used for iterating over.
  24. //
  25. // example:
  26. // Query a store and iterate over the results.
  27. //
  28. // | store.query({ prime: true }).forEach(function(item){
  29. // | // do something
  30. // | });
  31. if(!results){
  32. return results;
  33. }
  34. // if it is a promise it may be frozen
  35. if(results.then){
  36. results = lang.delegate(results);
  37. }
  38. function addIterativeMethod(method){
  39. if(!results[method]){
  40. results[method] = function(){
  41. var args = arguments;
  42. return Deferred.when(results, function(results){
  43. Array.prototype.unshift.call(args, results);
  44. return util.QueryResults(array[method].apply(array, args));
  45. });
  46. };
  47. }
  48. }
  49. addIterativeMethod("forEach");
  50. addIterativeMethod("filter");
  51. addIterativeMethod("map");
  52. if(!results.total){
  53. results.total = Deferred.when(results, function(results){
  54. return results.length;
  55. });
  56. }
  57. return results;
  58. };
  59. return util.QueryResults;
  60. });