]>
Commit | Line | Data |
---|---|---|
1354d172 AD |
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 | ||
8 | var util = lang.getObject("dojo.store.util", true); | |
9 | ||
10 | 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 | ||
34 | if(!results){ | |
35 | return results; | |
36 | } | |
37 | // if it is a promise it may be frozen | |
38 | if(results.then){ | |
39 | results = lang.delegate(results); | |
40 | } | |
41 | function addIterativeMethod(method){ | |
42 | if(!results[method]){ | |
43 | results[method] = function(){ | |
44 | var args = arguments; | |
45 | return Deferred.when(results, function(results){ | |
46 | Array.prototype.unshift.call(args, results); | |
47 | return util.QueryResults(array[method].apply(array, args)); | |
48 | }); | |
49 | }; | |
50 | } | |
51 | } | |
52 | addIterativeMethod("forEach"); | |
53 | addIterativeMethod("filter"); | |
54 | addIterativeMethod("map"); | |
55 | if(!results.total){ | |
56 | results.total = Deferred.when(results, function(results){ | |
57 | return results.length; | |
58 | }); | |
59 | } | |
60 | return results; | |
61 | }; | |
62 | ||
63 | return util.QueryResults; | |
64 | }); |