Roo/tree/TreeLoader.js
[roojs1] / Roo / tree / TreeLoader.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  * @class Roo.tree.TreeLoader
13  * @extends Roo.util.Observable
14  * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
15  * nodes from a specified URL. The response must be a javascript Array definition
16  * who's elements are node definition objects. eg:
17  * <pre><code>
18    [{ 'id': 1, 'text': 'A folder Node', 'leaf': false },
19     { 'id': 2, 'text': 'A leaf Node', 'leaf': true }]
20 </code></pre>
21  * <br><br>
22  * A server request is sent, and child nodes are loaded only when a node is expanded.
23  * The loading node's id is passed to the server under the parameter name "node" to
24  * enable the server to produce the correct child nodes.
25  * <br><br>
26  * To pass extra parameters, an event handler may be attached to the "beforeload"
27  * event, and the parameters specified in the TreeLoader's baseParams property:
28  * <pre><code>
29     myTreeLoader.on("beforeload", function(treeLoader, node) {
30         this.baseParams.category = node.attributes.category;
31     }, this);
32 </code></pre><
33  * This would pass an HTTP parameter called "category" to the server containing
34  * the value of the Node's "category" attribute.
35  * @constructor
36  * Creates a new Treeloader.
37  * @param {Object} config A config object containing config properties.
38  */
39 Roo.tree.TreeLoader = function(config){
40     this.baseParams = {};
41     this.requestMethod = "POST";
42     Roo.apply(this, config);
43
44     this.addEvents({
45         /**
46          * @event beforeload
47          * Fires before a network request is made to retrieve the Json text which specifies a node's children.
48          * @param {Object} This TreeLoader object.
49          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
50          * @param {Object} callback The callback function specified in the {@link #load} call.
51          */
52         beforeload : true,
53         /**
54          * @event load
55          * Fires when the node has been successfuly loaded.
56          * @param {Object} This TreeLoader object.
57          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
58          * @param {Object} response The response object containing the data from the server.
59          */
60         load : true,
61         /**
62          * @event loadexception
63          * Fires if the network request failed.
64          * @param {Object} This TreeLoader object.
65          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
66          * @param {Object} response The response object containing the data from the server.
67          */
68         loadexception : true,
69         /**
70          * @event create
71          * Fires before a node is created, enabling you to return custom Node types 
72          * @param {Object} This TreeLoader object.
73          * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
74          */
75         create : true
76     });
77
78     Roo.tree.TreeLoader.superclass.constructor.call(this);
79 };
80
81 Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
82     /**
83     * @cfg {String} dataUrl The URL from which to request a Json string which
84     * specifies an array of node definition object representing the child nodes
85     * to be loaded.
86     */
87     /**
88     * @cfg {Object} baseParams (optional) An object containing properties which
89     * specify HTTP parameters to be passed to each request for child nodes.
90     */
91     /**
92     * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
93     * created by this loader. If the attributes sent by the server have an attribute in this object,
94     * they take priority.
95     */
96     /**
97     * @cfg {Object} uiProviders (optional) An object containing properties which
98     * 
99     * DEPRECIATED - use 'create' event handler to modify attributes - which affect creation.
100     * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
101     * <i>uiProvider</i> attribute of a returned child node is a string rather
102     * than a reference to a TreeNodeUI implementation, this that string value
103     * is used as a property name in the uiProviders object. You can define the provider named
104     * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
105     */
106     uiProviders : {},
107
108     /**
109     * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
110     * child nodes before loading.
111     */
112     clearOnLoad : true,
113
114     /**
115     * @cfg {String} root (optional) Default to false. Use this to read data from an object 
116     * property on loading, rather than expecting an array. (eg. more compatible to a standard
117     * Grid query { data : [ .....] }
118     */
119     
120     root : false,
121      /**
122     * @cfg {String} queryParam (optional) 
123     * Name of the query as it will be passed on the querystring (defaults to 'node')
124     * eg. the request will be ?node=[id]
125     */
126     
127     
128     queryParam: false,
129     
130     /**
131      * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
132      * This is called automatically when a node is expanded, but may be used to reload
133      * a node (or append new children if the {@link #clearOnLoad} option is false.)
134      * @param {Roo.tree.TreeNode} node
135      * @param {Function} callback
136      */
137     load : function(node, callback){
138         if(this.clearOnLoad){
139             while(node.firstChild){
140                 node.removeChild(node.firstChild);
141             }
142         }
143         if(node.attributes.children){ // preloaded json children
144             var cs = node.attributes.children;
145             for(var i = 0, len = cs.length; i < len; i++){
146                 node.appendChild(this.createNode(cs[i]));
147             }
148             if(typeof callback == "function"){
149                 callback();
150             }
151         }else if(this.dataUrl){
152             this.requestData(node, callback);
153         }
154     },
155
156     getParams: function(node){
157         var buf = [], bp = this.baseParams;
158         for(var key in bp){
159             if(typeof bp[key] != "function"){
160                 buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
161             }
162         }
163         var n = this.queryParam === false ? 'node' : this.queryParam;
164         buf.push(n + "=", encodeURIComponent(node.id));
165         return buf.join("");
166     },
167
168     requestData : function(node, callback){
169         if(this.fireEvent("beforeload", this, node, callback) !== false){
170             this.transId = Roo.Ajax.request({
171                 method:this.requestMethod,
172                 url: this.dataUrl||this.url,
173                 success: this.handleResponse,
174                 failure: this.handleFailure,
175                 scope: this,
176                 argument: {callback: callback, node: node},
177                 params: this.getParams(node)
178             });
179         }else{
180             // if the load is cancelled, make sure we notify
181             // the node that we are done
182             if(typeof callback == "function"){
183                 callback();
184             }
185         }
186     },
187
188     isLoading : function(){
189         return this.transId ? true : false;
190     },
191
192     abort : function(){
193         if(this.isLoading()){
194             Roo.Ajax.abort(this.transId);
195         }
196     },
197
198     // private
199     createNode : function(attr){
200         // apply baseAttrs, nice idea Corey!
201         if(this.baseAttrs){
202             Roo.applyIf(attr, this.baseAttrs);
203         }
204         if(this.applyLoader !== false){
205             attr.loader = this;
206         }
207         // uiProvider = depreciated..
208         
209         if(typeof(attr.uiProvider) == 'string'){
210            attr.uiProvider = this.uiProviders[attr.uiProvider] || 
211                 /**  eval:var:attr */ eval(attr.uiProvider);
212         }
213         if(typeof(this.uiProviders['default']) != 'undefined') {
214             attr.uiProvider = this.uiProviders['default'];
215         }
216         
217         this.fireEvent('create', this, attr);
218         
219         attr.leaf  = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
220         return(attr.leaf ?
221                         new Roo.tree.TreeNode(attr) :
222                         new Roo.tree.AsyncTreeNode(attr));
223     },
224
225     processResponse : function(response, node, callback){
226         var json = response.responseText;
227         try {
228             
229             var o = /**  eval:var:zzzzzzzzzz */ eval("("+json+")");
230             if (this.root !== false) {
231                 o = o[this.root];
232             }
233             
234             for(var i = 0, len = o.length; i < len; i++){
235                 var n = this.createNode(o[i]);
236                 if(n){
237                     node.appendChild(n);
238                 }
239             }
240             if(typeof callback == "function"){
241                 callback(this, node);
242             }
243         }catch(e){
244             this.handleFailure(response);
245         }
246     },
247
248     handleResponse : function(response){
249         this.transId = false;
250         var a = response.argument;
251         this.processResponse(response, a.node, a.callback);
252         this.fireEvent("load", this, a.node, response);
253     },
254
255     handleFailure : function(response){
256         this.transId = false;
257         var a = response.argument;
258         this.fireEvent("loadexception", this, a.node, response);
259         if(typeof a.callback == "function"){
260             a.callback(this, a.node);
261         }
262     }
263 });