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