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