Upgrade to ExtJS 3.0.3 - Released 10/11/2009
[extjs.git] / src / widgets / tree / TreeLoader.js
1 /*!
2  * Ext JS Library 3.0.3
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**\r
8  * @class Ext.tree.TreeLoader\r
9  * @extends Ext.util.Observable\r
10  * A TreeLoader provides for lazy loading of an {@link Ext.tree.TreeNode}'s child\r
11  * nodes from a specified URL. The response must be a JavaScript Array definition\r
12  * whose elements are node definition objects. e.g.:\r
13  * <pre><code>\r
14     [{\r
15         id: 1,\r
16         text: 'A leaf Node',\r
17         leaf: true\r
18     },{\r
19         id: 2,\r
20         text: 'A folder Node',\r
21         children: [{\r
22             id: 3,\r
23             text: 'A child Node',\r
24             leaf: true\r
25         }]\r
26    }]\r
27 </code></pre>\r
28  * <br><br>\r
29  * A server request is sent, and child nodes are loaded only when a node is expanded.\r
30  * The loading node's id is passed to the server under the parameter name "node" to\r
31  * enable the server to produce the correct child nodes.\r
32  * <br><br>\r
33  * To pass extra parameters, an event handler may be attached to the "beforeload"\r
34  * event, and the parameters specified in the TreeLoader's baseParams property:\r
35  * <pre><code>\r
36     myTreeLoader.on("beforeload", function(treeLoader, node) {\r
37         this.baseParams.category = node.attributes.category;\r
38     }, this);\r
39 </code></pre>\r
40  * This would pass an HTTP parameter called "category" to the server containing\r
41  * the value of the Node's "category" attribute.\r
42  * @constructor\r
43  * Creates a new Treeloader.\r
44  * @param {Object} config A config object containing config properties.\r
45  */\r
46 Ext.tree.TreeLoader = function(config){\r
47     this.baseParams = {};\r
48     Ext.apply(this, config);\r
49 \r
50     this.addEvents(\r
51         /**\r
52          * @event beforeload\r
53          * Fires before a network request is made to retrieve the Json text which specifies a node's children.\r
54          * @param {Object} This TreeLoader object.\r
55          * @param {Object} node The {@link Ext.tree.TreeNode} object being loaded.\r
56          * @param {Object} callback The callback function specified in the {@link #load} call.\r
57          */\r
58         "beforeload",\r
59         /**\r
60          * @event load\r
61          * Fires when the node has been successfuly loaded.\r
62          * @param {Object} This TreeLoader object.\r
63          * @param {Object} node The {@link Ext.tree.TreeNode} object being loaded.\r
64          * @param {Object} response The response object containing the data from the server.\r
65          */\r
66         "load",\r
67         /**\r
68          * @event loadexception\r
69          * Fires if the network request failed.\r
70          * @param {Object} This TreeLoader object.\r
71          * @param {Object} node The {@link Ext.tree.TreeNode} object being loaded.\r
72          * @param {Object} response The response object containing the data from the server.\r
73          */\r
74         "loadexception"\r
75     );\r
76     Ext.tree.TreeLoader.superclass.constructor.call(this);\r
77     if(typeof this.paramOrder == 'string'){\r
78         this.paramOrder = this.paramOrder.split(/[\s,|]/);\r
79     }\r
80 };\r
81 \r
82 Ext.extend(Ext.tree.TreeLoader, Ext.util.Observable, {\r
83     /**\r
84     * @cfg {String} dataUrl The URL from which to request a Json string which\r
85     * specifies an array of node definition objects representing the child nodes\r
86     * to be loaded.\r
87     */\r
88     /**\r
89      * @cfg {String} requestMethod The HTTP request method for loading data (defaults to the value of {@link Ext.Ajax#method}).\r
90      */\r
91     /**\r
92      * @cfg {String} url Equivalent to {@link #dataUrl}.\r
93      */\r
94     /**\r
95      * @cfg {Boolean} preloadChildren If set to true, the loader recursively loads "children" attributes when doing the first load on nodes.\r
96      */\r
97     /**\r
98     * @cfg {Object} baseParams (optional) An object containing properties which\r
99     * specify HTTP parameters to be passed to each request for child nodes.\r
100     */\r
101     /**\r
102     * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes\r
103     * created by this loader. If the attributes sent by the server have an attribute in this object,\r
104     * they take priority.\r
105     */\r
106     /**\r
107     * @cfg {Object} uiProviders (optional) An object containing properties which\r
108     * specify custom {@link Ext.tree.TreeNodeUI} implementations. If the optional\r
109     * <i>uiProvider</i> attribute of a returned child node is a string rather\r
110     * than a reference to a TreeNodeUI implementation, then that string value\r
111     * is used as a property name in the uiProviders object.\r
112     */\r
113     uiProviders : {},\r
114 \r
115     /**\r
116     * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing\r
117     * child nodes before loading.\r
118     */\r
119     clearOnLoad : true,\r
120 \r
121     /**\r
122      * @cfg {Array/String} paramOrder Defaults to <tt>undefined</tt>. Only used when using directFn.\r
123      * A list of params to be executed\r
124      * server side.  Specify the params in the order in which they must be executed on the server-side\r
125      * as either (1) an Array of String values, or (2) a String of params delimited by either whitespace,\r
126      * comma, or pipe. For example,\r
127      * any of the following would be acceptable:<pre><code>\r
128 paramOrder: ['param1','param2','param3']\r
129 paramOrder: 'param1 param2 param3'\r
130 paramOrder: 'param1,param2,param3'\r
131 paramOrder: 'param1|param2|param'\r
132      </code></pre>\r
133      */\r
134     paramOrder: undefined,\r
135 \r
136     /**\r
137      * @cfg {Boolean} paramsAsHash Only used when using directFn.\r
138      * Send parameters as a collection of named arguments (defaults to <tt>false</tt>). Providing a\r
139      * <tt>{@link #paramOrder}</tt> nullifies this configuration.\r
140      */\r
141     paramsAsHash: false,\r
142 \r
143     /**\r
144      * @cfg {Function} directFn\r
145      * Function to call when executing a request.\r
146      */\r
147     directFn : undefined,\r
148 \r
149     /**\r
150      * Load an {@link Ext.tree.TreeNode} from the URL specified in the constructor.\r
151      * This is called automatically when a node is expanded, but may be used to reload\r
152      * a node (or append new children if the {@link #clearOnLoad} option is false.)\r
153      * @param {Ext.tree.TreeNode} node\r
154      * @param {Function} callback\r
155      * @param (Object) scope\r
156      */\r
157     load : function(node, callback, scope){\r
158         if(this.clearOnLoad){\r
159             while(node.firstChild){\r
160                 node.removeChild(node.firstChild);\r
161             }\r
162         }\r
163         if(this.doPreload(node)){ // preloaded json children\r
164             this.runCallback(callback, scope || node, [node]);\r
165         }else if(this.directFn || this.dataUrl || this.url){\r
166             this.requestData(node, callback, scope || node);\r
167         }\r
168     },\r
169 \r
170     doPreload : function(node){\r
171         if(node.attributes.children){\r
172             if(node.childNodes.length < 1){ // preloaded?\r
173                 var cs = node.attributes.children;\r
174                 node.beginUpdate();\r
175                 for(var i = 0, len = cs.length; i < len; i++){\r
176                     var cn = node.appendChild(this.createNode(cs[i]));\r
177                     if(this.preloadChildren){\r
178                         this.doPreload(cn);\r
179                     }\r
180                 }\r
181                 node.endUpdate();\r
182             }\r
183             return true;\r
184         }\r
185         return false;\r
186     },\r
187 \r
188     getParams: function(node){\r
189         var buf = [], bp = this.baseParams;\r
190         if(this.directFn){\r
191             buf.push(node.id);\r
192             if(bp){\r
193                 if(this.paramOrder){\r
194                     for(var i = 0, len = this.paramOrder.length; i < len; i++){\r
195                         buf.push(bp[this.paramOrder[i]]);\r
196                     }\r
197                 }else if(this.paramsAsHash){\r
198                     buf.push(bp);\r
199                 }\r
200             }\r
201             return buf;\r
202         }else{\r
203             for(var key in bp){\r
204                 if(!Ext.isFunction(bp[key])){\r
205                     buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");\r
206                 }\r
207             }\r
208             buf.push("node=", encodeURIComponent(node.id));\r
209             return buf.join("");\r
210         }\r
211     },\r
212 \r
213     requestData : function(node, callback, scope){\r
214         if(this.fireEvent("beforeload", this, node, callback) !== false){\r
215             if(this.directFn){\r
216                 var args = this.getParams(node);\r
217                 args.push(this.processDirectResponse.createDelegate(this, [{callback: callback, node: node, scope: scope}], true));\r
218                 this.directFn.apply(window, args);\r
219             }else{\r
220                 this.transId = Ext.Ajax.request({\r
221                     method:this.requestMethod,\r
222                     url: this.dataUrl||this.url,\r
223                     success: this.handleResponse,\r
224                     failure: this.handleFailure,\r
225                     scope: this,\r
226                     argument: {callback: callback, node: node, scope: scope},\r
227                     params: this.getParams(node)\r
228                 });\r
229             }\r
230         }else{\r
231             // if the load is cancelled, make sure we notify\r
232             // the node that we are done\r
233             this.runCallback(callback, scope || node, []);\r
234         }\r
235     },\r
236 \r
237     processDirectResponse: function(result, response, args){\r
238         if(response.status){\r
239             this.handleResponse({\r
240                 responseData: Ext.isArray(result) ? result : null,\r
241                 responseText: result,\r
242                 argument: args\r
243             });\r
244         }else{\r
245             this.handleFailure({\r
246                 argument: args\r
247             });\r
248         }\r
249     },\r
250 \r
251     // private\r
252     runCallback: function(cb, scope, args){\r
253         if(Ext.isFunction(cb)){\r
254             cb.apply(scope, args);\r
255         }\r
256     },\r
257 \r
258     isLoading : function(){\r
259         return !!this.transId;\r
260     },\r
261 \r
262     abort : function(){\r
263         if(this.isLoading()){\r
264             Ext.Ajax.abort(this.transId);\r
265         }\r
266     },\r
267 \r
268     /**\r
269     * <p>Override this function for custom TreeNode node implementation, or to\r
270     * modify the attributes at creation time.</p>\r
271     * Example:<pre><code>\r
272 new Ext.tree.TreePanel({\r
273     ...\r
274     loader: new Ext.tree.TreeLoader({\r
275         url: 'dataUrl',\r
276         createNode: function(attr) {\r
277 //          Allow consolidation consignments to have\r
278 //          consignments dropped into them.\r
279             if (attr.isConsolidation) {\r
280                 attr.iconCls = 'x-consol',\r
281                 attr.allowDrop = true;\r
282             }\r
283             return Ext.tree.TreeLoader.prototype.createNode.call(this, attr);\r
284         }\r
285     }),\r
286     ...\r
287 });\r
288 </code></pre>\r
289     * @param attr {Object} The attributes from which to create the new node.\r
290     */\r
291     createNode : function(attr){\r
292         // apply baseAttrs, nice idea Corey!\r
293         if(this.baseAttrs){\r
294             Ext.applyIf(attr, this.baseAttrs);\r
295         }\r
296         if(this.applyLoader !== false && !attr.loader){\r
297             attr.loader = this;\r
298         }\r
299         if(typeof attr.uiProvider == 'string'){\r
300            attr.uiProvider = this.uiProviders[attr.uiProvider] || eval(attr.uiProvider);\r
301         }\r
302         if(attr.nodeType){\r
303             return new Ext.tree.TreePanel.nodeTypes[attr.nodeType](attr);\r
304         }else{\r
305             return attr.leaf ?\r
306                         new Ext.tree.TreeNode(attr) :\r
307                         new Ext.tree.AsyncTreeNode(attr);\r
308         }\r
309     },\r
310 \r
311     processResponse : function(response, node, callback, scope){\r
312         var json = response.responseText;\r
313         try {\r
314             var o = response.responseData || Ext.decode(json);\r
315             node.beginUpdate();\r
316             for(var i = 0, len = o.length; i < len; i++){\r
317                 var n = this.createNode(o[i]);\r
318                 if(n){\r
319                     node.appendChild(n);\r
320                 }\r
321             }\r
322             node.endUpdate();\r
323             this.runCallback(callback, scope || node, [node]);\r
324         }catch(e){\r
325             this.handleFailure(response);\r
326         }\r
327     },\r
328 \r
329     handleResponse : function(response){\r
330         this.transId = false;\r
331         var a = response.argument;\r
332         this.processResponse(response, a.node, a.callback, a.scope);\r
333         this.fireEvent("load", this, a.node, response);\r
334     },\r
335 \r
336     handleFailure : function(response){\r
337         this.transId = false;\r
338         var a = response.argument;\r
339         this.fireEvent("loadexception", this, a.node, response);\r
340         this.runCallback(a.callback, a.scope || a.node, [a.node]);\r
341     }\r
342 });