initial import
[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
71     Roo.tree.TreeLoader.superclass.constructor.call(this);
72 };
73
74 Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
75     /**
76     * @cfg {String} dataUrl The URL from which to request a Json string which
77     * specifies an array of node definition object representing the child nodes
78     * to be loaded.
79     */
80     /**
81     * @cfg {Object} baseParams (optional) An object containing properties which
82     * specify HTTP parameters to be passed to each request for child nodes.
83     */
84     /**
85     * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
86     * created by this loader. If the attributes sent by the server have an attribute in this object,
87     * they take priority.
88     */
89     /**
90     * @cfg {Object} uiProviders (optional) An object containing properties which
91     * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
92     * <i>uiProvider</i> attribute of a returned child node is a string rather
93     * than a reference to a TreeNodeUI implementation, this that string value
94     * is used as a property name in the uiProviders object. You can define the provider named
95     * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
96     */
97     uiProviders : {},
98
99     /**
100     * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
101     * child nodes before loading.
102     */
103     clearOnLoad : true,
104
105     /**
106     * @cfg {String} root (optional) Default to false. Use this to read data from an object 
107     * property on loading, rather than expecting an array. (eg. more compatible to a standard
108     * Grid query { data : [ .....] }
109     */
110     
111     root : false,
112      /**
113     * @cfg {String} queryParam (optional) 
114     * Name of the query as it will be passed on the querystring (defaults to 'node')
115     * eg. the request will be ?node=[id]
116     */
117     
118     
119     queryParam: false,
120     
121     /**
122      * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
123      * This is called automatically when a node is expanded, but may be used to reload
124      * a node (or append new children if the {@link #clearOnLoad} option is false.)
125      * @param {Roo.tree.TreeNode} node
126      * @param {Function} callback
127      */
128     load : function(node, callback){
129         if(this.clearOnLoad){
130             while(node.firstChild){
131                 node.removeChild(node.firstChild);
132             }
133         }
134         if(node.attributes.children){ // preloaded json children
135             var cs = node.attributes.children;
136             for(var i = 0, len = cs.length; i < len; i++){
137                 node.appendChild(this.createNode(cs[i]));
138             }
139             if(typeof callback == "function"){
140                 callback();
141             }
142         }else if(this.dataUrl){
143             this.requestData(node, callback);
144         }
145     },
146
147     getParams: function(node){
148         var buf = [], bp = this.baseParams;
149         for(var key in bp){
150             if(typeof bp[key] != "function"){
151                 buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
152             }
153         }
154         var n = this.queryParam === false ? 'node' : this.queryParam;
155         buf.push(n + "=", encodeURIComponent(node.id));
156         return buf.join("");
157     },
158
159     requestData : function(node, callback){
160         if(this.fireEvent("beforeload", this, node, callback) !== false){
161             this.transId = Roo.Ajax.request({
162                 method:this.requestMethod,
163                 url: this.dataUrl||this.url,
164                 success: this.handleResponse,
165                 failure: this.handleFailure,
166                 scope: this,
167                 argument: {callback: callback, node: node},
168                 params: this.getParams(node)
169             });
170         }else{
171             // if the load is cancelled, make sure we notify
172             // the node that we are done
173             if(typeof callback == "function"){
174                 callback();
175             }
176         }
177     },
178
179     isLoading : function(){
180         return this.transId ? true : false;
181     },
182
183     abort : function(){
184         if(this.isLoading()){
185             Roo.Ajax.abort(this.transId);
186         }
187     },
188
189     /**
190     * Override this function for custom TreeNode node implementation
191     */
192     createNode : function(attr){
193         // apply baseAttrs, nice idea Corey!
194         if(this.baseAttrs){
195             Roo.applyIf(attr, this.baseAttrs);
196         }
197         if(this.applyLoader !== false){
198             attr.loader = this;
199         }
200         if(typeof(attr.uiProvider) == 'string'){
201             
202            attr.uiProvider = this.uiProviders[attr.uiProvider] || 
203                 /**  eval:var:attr */ eval(attr.uiProvider);
204         }
205         if(typeof(this.uiProviders['default']) != 'undefined') {
206             attr.uiProvider = this.uiProviders['default'];
207         }
208         attr.leaf  = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
209         return(attr.leaf ?
210                         new Roo.tree.TreeNode(attr) :
211                         new Roo.tree.AsyncTreeNode(attr));
212     },
213
214     processResponse : function(response, node, callback){
215         var json = response.responseText;
216         try {
217             
218             var o = /**  eval:var:zzzzzzzzzz */ eval("("+json+")");
219             if (this.root !== false) {
220                 o = o[this.root];
221             }
222             
223             for(var i = 0, len = o.length; i < len; i++){
224                 var n = this.createNode(o[i]);
225                 if(n){
226                     node.appendChild(n);
227                 }
228             }
229             if(typeof callback == "function"){
230                 callback(this, node);
231             }
232         }catch(e){
233             this.handleFailure(response);
234         }
235     },
236
237     handleResponse : function(response){
238         this.transId = false;
239         var a = response.argument;
240         this.processResponse(response, a.node, a.callback);
241         this.fireEvent("load", this, a.node, response);
242     },
243
244     handleFailure : function(response){
245         this.transId = false;
246         var a = response.argument;
247         this.fireEvent("loadexception", this, a.node, response);
248         if(typeof a.callback == "function"){
249             a.callback(this, a.node);
250         }
251     }
252 });