Roo/JsonView.js
[roojs1] / Roo / JsonView.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11
12 /**
13  * @class Roo.JsonView
14  * @extends Roo.View
15  * Shortcut class to create a JSON + {@link Roo.UpdateManager} template view. Usage:
16 <pre><code>
17 var view = new Roo.JsonView({
18     container: "my-element",
19     tpl: '&lt;div id="{id}"&gt;{foo} - {bar}&lt;/div&gt;', // auto create template
20     multiSelect: true, 
21     jsonRoot: "data" 
22 });
23
24 // listen for node click?
25 view.on("click", function(vw, index, node, e){
26     alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
27 });
28
29 // direct load of JSON data
30 view.load("foobar.php");
31
32 // Example from my blog list
33 var tpl = new Roo.Template(
34     '&lt;div class="entry"&gt;' +
35     '&lt;a class="entry-title" href="{link}"&gt;{title}&lt;/a&gt;' +
36     "&lt;h4&gt;{date} by {author} | {comments} Comments&lt;/h4&gt;{description}" +
37     "&lt;/div&gt;&lt;hr /&gt;"
38 );
39
40 var moreView = new Roo.JsonView({
41     container :  "entry-list", 
42     template : tpl,
43     jsonRoot: "posts"
44 });
45 moreView.on("beforerender", this.sortEntries, this);
46 moreView.load({
47     url: "/blog/get-posts.php",
48     params: "allposts=true",
49     text: "Loading Blog Entries..."
50 });
51 </code></pre>
52
53 * Note: old code is supported with arguments : (container, template, config)
54
55
56  * @constructor
57  * Create a new JsonView
58  * 
59  * @param {Object} config The config object
60  * 
61  */
62 Roo.JsonView = function(config, depreciated_tpl, depreciated_config){
63     
64     
65     Roo.JsonView.superclass.constructor.call(this, config, depreciated_tpl, depreciated_config);
66
67     var um = this.el.getUpdateManager();
68     um.setRenderer(this);
69     um.on("update", this.onLoad, this);
70     um.on("failure", this.onLoadException, this);
71
72     /**
73      * @event beforerender
74      * Fires before rendering of the downloaded JSON data.
75      * @param {Roo.JsonView} this
76      * @param {Object} data The JSON data loaded
77      */
78     /**
79      * @event load
80      * Fires when data is loaded.
81      * @param {Roo.JsonView} this
82      * @param {Object} data The JSON data loaded
83      * @param {Object} response The raw Connect response object
84      */
85     /**
86      * @event loadexception
87      * Fires when loading fails.
88      * @param {Roo.JsonView} this
89      * @param {Object} response The raw Connect response object
90      */
91     this.addEvents({
92         'beforerender' : true,
93         'load' : true,
94         'loadexception' : true
95     });
96 };
97 Roo.extend(Roo.JsonView, Roo.View, {
98     /**
99      * @type {String} The root property in the loaded JSON object that contains the data
100      */
101     jsonRoot : "",
102
103     /**
104      * Refreshes the view.
105      */
106     refresh : function(){
107         this.clearSelections();
108         this.el.update("");
109         var html = [];
110         var o = this.jsonData;
111         if(o && o.length > 0){
112             for(var i = 0, len = o.length; i < len; i++){
113                 var data = this.prepareData(o[i], i, o);
114                 html[html.length] = this.tpl.apply(data);
115             }
116         }else{
117             html.push(this.emptyText);
118         }
119         this.el.update(html.join(""));
120         this.nodes = this.el.dom.childNodes;
121         this.updateIndexes(0);
122     },
123
124     /**
125      * Performs an async HTTP request, and loads the JSON from the response. If <i>params</i> are specified it uses POST, otherwise it uses GET.
126      * @param {Object/String/Function} url The URL for this request, or a function to call to get the URL, or a config object containing any of the following options:
127      <pre><code>
128      view.load({
129          url: "your-url.php",
130          params: {param1: "foo", param2: "bar"}, // or a URL encoded string
131          callback: yourFunction,
132          scope: yourObject, //(optional scope)
133          discardUrl: false,
134          nocache: false,
135          text: "Loading...",
136          timeout: 30,
137          scripts: false
138      });
139      </code></pre>
140      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
141      * are respectively shorthand for <i>disableCaching</i>, <i>indicatorText</i>, and <i>loadScripts</i> and are used to set their associated property on this UpdateManager instance.
142      * @param {String/Object} params (optional) The parameters to pass, as either a URL encoded string "param1=1&amp;param2=2" or an object {param1: 1, param2: 2}
143      * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
144      * @param {Boolean} discardUrl (optional) By default when you execute an update the defaultUrl is changed to the last used URL. If true, it will not store the URL.
145      */
146     load : function(){
147         var um = this.el.getUpdateManager();
148         um.update.apply(um, arguments);
149     },
150
151     // note - render is a standard framework call...
152     // using it for the response is really flaky... - it's called by UpdateManager normally, except when called by the XComponent/addXtype.
153     render : function(el, response){
154         
155         this.clearSelections();
156         this.el.update("");
157         var o;
158         try{
159             if (response != '') {
160                     
161                 }
162                 o = Roo.util.JSON.decode(response.responseText);
163                 if(this.jsonRoot){
164                     
165                     o = o[this.jsonRoot];
166                 }
167         }
168         } catch(e){
169         }
170         /**
171          * The current JSON data or null
172          */
173         this.jsonData = o;
174         this.beforeRender();
175         this.refresh();
176     },
177
178 /**
179  * Get the number of records in the current JSON dataset
180  * @return {Number}
181  */
182     getCount : function(){
183         return this.jsonData ? this.jsonData.length : 0;
184     },
185
186 /**
187  * Returns the JSON object for the specified node(s)
188  * @param {HTMLElement/Array} node The node or an array of nodes
189  * @return {Object/Array} If you pass in an array, you get an array back, otherwise
190  * you get the JSON object for the node
191  */
192     getNodeData : function(node){
193         if(node instanceof Array){
194             var data = [];
195             for(var i = 0, len = node.length; i < len; i++){
196                 data.push(this.getNodeData(node[i]));
197             }
198             return data;
199         }
200         return this.jsonData[this.indexOf(node)] || null;
201     },
202
203     beforeRender : function(){
204         this.snapshot = this.jsonData;
205         if(this.sortInfo){
206             this.sort.apply(this, this.sortInfo);
207         }
208         this.fireEvent("beforerender", this, this.jsonData);
209     },
210
211     onLoad : function(el, o){
212         this.fireEvent("load", this, this.jsonData, o);
213     },
214
215     onLoadException : function(el, o){
216         this.fireEvent("loadexception", this, o);
217     },
218
219 /**
220  * Filter the data by a specific property.
221  * @param {String} property A property on your JSON objects
222  * @param {String/RegExp} value Either string that the property values
223  * should start with, or a RegExp to test against the property
224  */
225     filter : function(property, value){
226         if(this.jsonData){
227             var data = [];
228             var ss = this.snapshot;
229             if(typeof value == "string"){
230                 var vlen = value.length;
231                 if(vlen == 0){
232                     this.clearFilter();
233                     return;
234                 }
235                 value = value.toLowerCase();
236                 for(var i = 0, len = ss.length; i < len; i++){
237                     var o = ss[i];
238                     if(o[property].substr(0, vlen).toLowerCase() == value){
239                         data.push(o);
240                     }
241                 }
242             } else if(value.exec){ // regex?
243                 for(var i = 0, len = ss.length; i < len; i++){
244                     var o = ss[i];
245                     if(value.test(o[property])){
246                         data.push(o);
247                     }
248                 }
249             } else{
250                 return;
251             }
252             this.jsonData = data;
253             this.refresh();
254         }
255     },
256
257 /**
258  * Filter by a function. The passed function will be called with each
259  * object in the current dataset. If the function returns true the value is kept,
260  * otherwise it is filtered.
261  * @param {Function} fn
262  * @param {Object} scope (optional) The scope of the function (defaults to this JsonView)
263  */
264     filterBy : function(fn, scope){
265         if(this.jsonData){
266             var data = [];
267             var ss = this.snapshot;
268             for(var i = 0, len = ss.length; i < len; i++){
269                 var o = ss[i];
270                 if(fn.call(scope || this, o)){
271                     data.push(o);
272                 }
273             }
274             this.jsonData = data;
275             this.refresh();
276         }
277     },
278
279 /**
280  * Clears the current filter.
281  */
282     clearFilter : function(){
283         if(this.snapshot && this.jsonData != this.snapshot){
284             this.jsonData = this.snapshot;
285             this.refresh();
286         }
287     },
288
289
290 /**
291  * Sorts the data for this view and refreshes it.
292  * @param {String} property A property on your JSON objects to sort on
293  * @param {String} direction (optional) "desc" or "asc" (defaults to "asc")
294  * @param {Function} sortType (optional) A function to call to convert the data to a sortable value.
295  */
296     sort : function(property, dir, sortType){
297         this.sortInfo = Array.prototype.slice.call(arguments, 0);
298         if(this.jsonData){
299             var p = property;
300             var dsc = dir && dir.toLowerCase() == "desc";
301             var f = function(o1, o2){
302                 var v1 = sortType ? sortType(o1[p]) : o1[p];
303                 var v2 = sortType ? sortType(o2[p]) : o2[p];
304                 ;
305                 if(v1 < v2){
306                     return dsc ? +1 : -1;
307                 } else if(v1 > v2){
308                     return dsc ? -1 : +1;
309                 } else{
310                     return 0;
311                 }
312             };
313             this.jsonData.sort(f);
314             this.refresh();
315             if(this.jsonData != this.snapshot){
316                 this.snapshot.sort(f);
317             }
318         }
319     }
320 });