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