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