Upgrade to ExtJS 3.1.0 - Released 12/16/2009
[extjs.git] / src / widgets / tree / TreeLoader.js
1 /*!
2  * Ext JS Library 3.1.0
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(Ext.isString(this.paramOrder)){\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 {String} nodeParameter The name of the parameter sent to the server which contains\r
145      * the identifier of the node. Defaults to <tt>'node'</tt>.\r
146      */\r
147     nodeParameter: 'node',\r
148 \r
149     /**\r
150      * @cfg {Function} directFn\r
151      * Function to call when executing a request.\r
152      */\r
153     directFn : undefined,\r
154 \r
155     /**\r
156      * Load an {@link Ext.tree.TreeNode} from the URL specified in the constructor.\r
157      * This is called automatically when a node is expanded, but may be used to reload\r
158      * a node (or append new children if the {@link #clearOnLoad} option is false.)\r
159      * @param {Ext.tree.TreeNode} node\r
160      * @param {Function} callback Function to call after the node has been loaded. The \r
161      * function is passed the TreeNode which was requested to be loaded.\r
162      * @param (Object) scope The cope (<code>this</code> reference) in which the callback is executed.\r
163      * defaults to the loaded TreeNode.\r
164      */\r
165     load : function(node, callback, scope){\r
166         if(this.clearOnLoad){\r
167             while(node.firstChild){\r
168                 node.removeChild(node.firstChild);\r
169             }\r
170         }\r
171         if(this.doPreload(node)){ // preloaded json children\r
172             this.runCallback(callback, scope || node, [node]);\r
173         }else if(this.directFn || this.dataUrl || this.url){\r
174             this.requestData(node, callback, scope || node);\r
175         }\r
176     },\r
177 \r
178     doPreload : function(node){\r
179         if(node.attributes.children){\r
180             if(node.childNodes.length < 1){ // preloaded?\r
181                 var cs = node.attributes.children;\r
182                 node.beginUpdate();\r
183                 for(var i = 0, len = cs.length; i < len; i++){\r
184                     var cn = node.appendChild(this.createNode(cs[i]));\r
185                     if(this.preloadChildren){\r
186                         this.doPreload(cn);\r
187                     }\r
188                 }\r
189                 node.endUpdate();\r
190             }\r
191             return true;\r
192         }\r
193         return false;\r
194     },\r
195 \r
196     getParams: function(node){\r
197         var buf = [], bp = this.baseParams;\r
198         if(this.directFn){\r
199             buf.push(node.id);\r
200             if(bp){\r
201                 if(this.paramOrder){\r
202                     for(var i = 0, len = this.paramOrder.length; i < len; i++){\r
203                         buf.push(bp[this.paramOrder[i]]);\r
204                     }\r
205                 }else if(this.paramsAsHash){\r
206                     buf.push(bp);\r
207                 }\r
208             }\r
209             return buf;\r
210         }else{\r
211             var o = Ext.apply({}, bp);\r
212             o[this.nodeParameter] = node.id;\r
213             return o;\r
214         }\r
215     },\r
216 \r
217     requestData : function(node, callback, scope){\r
218         if(this.fireEvent("beforeload", this, node, callback) !== false){\r
219             if(this.directFn){\r
220                 var args = this.getParams(node);\r
221                 args.push(this.processDirectResponse.createDelegate(this, [{callback: callback, node: node, scope: scope}], true));\r
222                 this.directFn.apply(window, args);\r
223             }else{\r
224                 this.transId = Ext.Ajax.request({\r
225                     method:this.requestMethod,\r
226                     url: this.dataUrl||this.url,\r
227                     success: this.handleResponse,\r
228                     failure: this.handleFailure,\r
229                     scope: this,\r
230                     argument: {callback: callback, node: node, scope: scope},\r
231                     params: this.getParams(node)\r
232                 });\r
233             }\r
234         }else{\r
235             // if the load is cancelled, make sure we notify\r
236             // the node that we are done\r
237             this.runCallback(callback, scope || node, []);\r
238         }\r
239     },\r
240 \r
241     processDirectResponse: function(result, response, args){\r
242         if(response.status){\r
243             this.handleResponse({\r
244                 responseData: Ext.isArray(result) ? result : null,\r
245                 responseText: result,\r
246                 argument: args\r
247             });\r
248         }else{\r
249             this.handleFailure({\r
250                 argument: args\r
251             });\r
252         }\r
253     },\r
254 \r
255     // private\r
256     runCallback: function(cb, scope, args){\r
257         if(Ext.isFunction(cb)){\r
258             cb.apply(scope, args);\r
259         }\r
260     },\r
261 \r
262     isLoading : function(){\r
263         return !!this.transId;\r
264     },\r
265 \r
266     abort : function(){\r
267         if(this.isLoading()){\r
268             Ext.Ajax.abort(this.transId);\r
269         }\r
270     },\r
271 \r
272     /**\r
273     * <p>Override this function for custom TreeNode node implementation, or to\r
274     * modify the attributes at creation time.</p>\r
275     * Example:<pre><code>\r
276 new Ext.tree.TreePanel({\r
277     ...\r
278     loader: new Ext.tree.TreeLoader({\r
279         url: 'dataUrl',\r
280         createNode: function(attr) {\r
281 //          Allow consolidation consignments to have\r
282 //          consignments dropped into them.\r
283             if (attr.isConsolidation) {\r
284                 attr.iconCls = 'x-consol',\r
285                 attr.allowDrop = true;\r
286             }\r
287             return Ext.tree.TreeLoader.prototype.createNode.call(this, attr);\r
288         }\r
289     }),\r
290     ...\r
291 });\r
292 </code></pre>\r
293     * @param attr {Object} The attributes from which to create the new node.\r
294     */\r
295     createNode : function(attr){\r
296         // apply baseAttrs, nice idea Corey!\r
297         if(this.baseAttrs){\r
298             Ext.applyIf(attr, this.baseAttrs);\r
299         }\r
300         if(this.applyLoader !== false && !attr.loader){\r
301             attr.loader = this;\r
302         }\r
303         if(Ext.isString(attr.uiProvider)){\r
304            attr.uiProvider = this.uiProviders[attr.uiProvider] || eval(attr.uiProvider);\r
305         }\r
306         if(attr.nodeType){\r
307             return new Ext.tree.TreePanel.nodeTypes[attr.nodeType](attr);\r
308         }else{\r
309             return attr.leaf ?\r
310                         new Ext.tree.TreeNode(attr) :\r
311                         new Ext.tree.AsyncTreeNode(attr);\r
312         }\r
313     },\r
314 \r
315     processResponse : function(response, node, callback, scope){\r
316         var json = response.responseText;\r
317         try {\r
318             var o = response.responseData || Ext.decode(json);\r
319             node.beginUpdate();\r
320             for(var i = 0, len = o.length; i < len; i++){\r
321                 var n = this.createNode(o[i]);\r
322                 if(n){\r
323                     node.appendChild(n);\r
324                 }\r
325             }\r
326             node.endUpdate();\r
327             this.runCallback(callback, scope || node, [node]);\r
328         }catch(e){\r
329             this.handleFailure(response);\r
330         }\r
331     },\r
332 \r
333     handleResponse : function(response){\r
334         this.transId = false;\r
335         var a = response.argument;\r
336         this.processResponse(response, a.node, a.callback, a.scope);\r
337         this.fireEvent("load", this, a.node, response);\r
338     },\r
339 \r
340     handleFailure : function(response){\r
341         this.transId = false;\r
342         var a = response.argument;\r
343         this.fireEvent("loadexception", this, a.node, response);\r
344         this.runCallback(a.callback, a.scope || a.node, [a.node]);\r
345     },\r
346     \r
347     destroy : function(){\r
348         this.purgeListeners();\r
349     }\r
350 });