QueryResults.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
  3. Available via Academic Free License >= 2.1 OR the modified BSD license.
  4. see: http://dojotoolkit.org/license for details
  5. */
  6. if(!dojo._hasResource["dojo.store.util.QueryResults"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
  7. dojo._hasResource["dojo.store.util.QueryResults"] = true;
  8. dojo.provide("dojo.store.util.QueryResults");
  9. dojo.getObject("store.util", true, dojo);
  10. dojo.store.util.QueryResults = function(results){
  11. // summary:
  12. // A function that wraps the results of a store query with additional
  13. // methods.
  14. //
  15. // description:
  16. // QueryResults is a basic wrapper that allows for array-like iteration
  17. // over any kind of returned data from a query. While the simplest store
  18. // will return a plain array of data, other stores may return deferreds or
  19. // promises; this wrapper makes sure that *all* results can be treated
  20. // the same.
  21. //
  22. // Additional methods include `forEach`, `filter` and `map`.
  23. //
  24. // returns: Object
  25. // An array-like object that can be used for iterating over.
  26. //
  27. // example:
  28. // Query a store and iterate over the results.
  29. //
  30. // | store.query({ prime: true }).forEach(function(item){
  31. // | // do something
  32. // | });
  33. if(!results){
  34. return results;
  35. }
  36. // if it is a promise it may be frozen
  37. if(results.then){
  38. results = dojo.delegate(results);
  39. }
  40. function addIterativeMethod(method){
  41. if(!results[method]){
  42. results[method] = function(){
  43. var args = arguments;
  44. return dojo.when(results, function(results){
  45. Array.prototype.unshift.call(args, results);
  46. return dojo.store.util.QueryResults(dojo[method].apply(dojo, args));
  47. });
  48. };
  49. }
  50. }
  51. addIterativeMethod("forEach");
  52. addIterativeMethod("filter");
  53. addIterativeMethod("map");
  54. if(!results.total){
  55. results.total = dojo.when(results, function(results){
  56. return results.length;
  57. });
  58. }
  59. return results;
  60. };
  61. }