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