Upgrade to ExtJS 3.0.3 - Released 10/11/2009
[extjs.git] / docs / source / DataProxy.html
1 <html>
2 <head>
3   <title>The source code</title>
4     <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
5     <script type="text/javascript" src="../resources/prettify/prettify.js"></script>
6 </head>
7 <body  onload="prettyPrint();">
8     <pre class="prettyprint lang-js">/*!
9  * Ext JS Library 3.0.3
10  * Copyright(c) 2006-2009 Ext JS, LLC
11  * licensing@extjs.com
12  * http://www.extjs.com/license
13  */
14 <div id="cls-Ext.data.DataProxy"></div>/**\r
15  * @class Ext.data.DataProxy\r
16  * @extends Ext.util.Observable\r
17  * <p>Abstract base class for implementations which provide retrieval of unformatted data objects.\r
18  * This class is intended to be extended and should not be created directly. For existing implementations,\r
19  * see {@link Ext.data.DirectProxy}, {@link Ext.data.HttpProxy}, {@link Ext.data.ScriptTagProxy} and\r
20  * {@link Ext.data.MemoryProxy}.</p>\r
21  * <p>DataProxy implementations are usually used in conjunction with an implementation of {@link Ext.data.DataReader}\r
22  * (of the appropriate type which knows how to parse the data object) to provide a block of\r
23  * {@link Ext.data.Records} to an {@link Ext.data.Store}.</p>\r
24  * <p>The parameter to a DataProxy constructor may be an {@link Ext.data.Connection} or can also be the\r
25  * config object to an {@link Ext.data.Connection}.</p>\r
26  * <p>Custom implementations must implement either the <code><b>doRequest</b></code> method (preferred) or the\r
27  * <code>load</code> method (deprecated). See\r
28  * {@link Ext.data.HttpProxy}.{@link Ext.data.HttpProxy#doRequest doRequest} or\r
29  * {@link Ext.data.HttpProxy}.{@link Ext.data.HttpProxy#load load} for additional details.</p>\r
30  * <p><b><u>Example 1</u></b></p>\r
31  * <pre><code>\r
32 proxy: new Ext.data.ScriptTagProxy({\r
33     {@link Ext.data.Connection#url url}: 'http://extjs.com/forum/topics-remote.php'\r
34 }),\r
35  * </code></pre>\r
36  * <p><b><u>Example 2</u></b></p>\r
37  * <pre><code>\r
38 proxy : new Ext.data.HttpProxy({\r
39     {@link Ext.data.Connection#method method}: 'GET',\r
40     {@link Ext.data.HttpProxy#prettyUrls prettyUrls}: false,\r
41     {@link Ext.data.Connection#url url}: 'local/default.php', // see options parameter for {@link Ext.Ajax#request}\r
42     {@link #api}: {\r
43         // all actions except the following will use above url\r
44         create  : 'local/new.php',\r
45         update  : 'local/update.php'\r
46     }\r
47 }),\r
48  * </code></pre>\r
49  */\r
50 Ext.data.DataProxy = function(conn){\r
51     // make sure we have a config object here to support ux proxies.\r
52     // All proxies should now send config into superclass constructor.\r
53     conn = conn || {};\r
54 \r
55     // This line caused a bug when people use custom Connection object having its own request method.\r
56     // http://extjs.com/forum/showthread.php?t=67194.  Have to set DataProxy config\r
57     //Ext.applyIf(this, conn);\r
58 \r
59     this.api     = conn.api;\r
60     this.url     = conn.url;\r
61     this.restful = conn.restful;\r
62     this.listeners = conn.listeners;\r
63 \r
64     // deprecated\r
65     this.prettyUrls = conn.prettyUrls;\r
66 \r
67     <div id="cfg-Ext.data.DataProxy-api"></div>/**\r
68      * @cfg {Object} api\r
69      * Specific urls to call on CRUD action methods "read", "create", "update" and "destroy".\r
70      * Defaults to:<pre><code>\r
71 api: {\r
72     read    : undefined,\r
73     create  : undefined,\r
74     update  : undefined,\r
75     destroy : undefined\r
76 }\r
77      * </code></pre>\r
78      * <p>The url is built based upon the action being executed <tt>[load|create|save|destroy]</tt>\r
79      * using the commensurate <tt>{@link #api}</tt> property, or if undefined default to the\r
80      * configured {@link Ext.data.Store}.{@link Ext.data.Store#url url}.</p><br>\r
81      * <p>For example:</p>\r
82      * <pre><code>\r
83 api: {\r
84     load :    '/controller/load',\r
85     create :  '/controller/new',  // Server MUST return idProperty of new record\r
86     save :    '/controller/update',\r
87     destroy : '/controller/destroy_action'\r
88 }\r
89 \r
90 // Alternatively, one can use the object-form to specify each API-action\r
91 api: {\r
92     load: {url: 'read.php', method: 'GET'},\r
93     create: 'create.php',\r
94     destroy: 'destroy.php',\r
95     save: 'update.php'\r
96 }\r
97      * </code></pre>\r
98      * <p>If the specific URL for a given CRUD action is undefined, the CRUD action request\r
99      * will be directed to the configured <tt>{@link Ext.data.Connection#url url}</tt>.</p>\r
100      * <br><p><b>Note</b>: To modify the URL for an action dynamically the appropriate API\r
101      * property should be modified before the action is requested using the corresponding before\r
102      * action event.  For example to modify the URL associated with the load action:\r
103      * <pre><code>\r
104 // modify the url for the action\r
105 myStore.on({\r
106     beforeload: {\r
107         fn: function (store, options) {\r
108             // use <tt>{@link Ext.data.HttpProxy#setUrl setUrl}</tt> to change the URL for *just* this request.\r
109             store.proxy.setUrl('changed1.php');\r
110 \r
111             // set optional second parameter to true to make this URL change\r
112             // permanent, applying this URL for all subsequent requests.\r
113             store.proxy.setUrl('changed1.php', true);\r
114 \r
115             // Altering the proxy API should be done using the public\r
116             // method <tt>{@link Ext.data.DataProxy#setApi setApi}</tt>.\r
117             store.proxy.setApi('read', 'changed2.php');\r
118 \r
119             // Or set the entire API with a config-object.\r
120             // When using the config-object option, you must redefine the <b>entire</b>\r
121             // API -- not just a specific action of it.\r
122             store.proxy.setApi({\r
123                 read    : 'changed_read.php',\r
124                 create  : 'changed_create.php',\r
125                 update  : 'changed_update.php',\r
126                 destroy : 'changed_destroy.php'\r
127             });\r
128         }\r
129     }\r
130 });\r
131      * </code></pre>\r
132      * </p>\r
133      */\r
134 \r
135     this.addEvents(\r
136         <div id="event-Ext.data.DataProxy-exception"></div>/**\r
137          * @event exception\r
138          * <p>Fires if an exception occurs in the Proxy during a remote request. This event is relayed\r
139          * through a corresponding {@link Ext.data.Store}.{@link Ext.data.Store#exception exception},\r
140          * so any Store instance may observe this event.</p>\r
141          * <p>In addition to being fired through the DataProxy instance that raised the event, this event is also fired\r
142          * through the Ext.data.DataProxy <i>class</i> to allow for centralized processing of exception events from <b>all</b>\r
143          * DataProxies by attaching a listener to the Ext.data.Proxy class itself.</p>\r
144          * <p>This event can be fired for one of two reasons:</p>\r
145          * <div class="mdetail-params"><ul>\r
146          * <li>remote-request <b>failed</b> : <div class="sub-desc">\r
147          * The server did not return status === 200.\r
148          * </div></li>\r
149          * <li>remote-request <b>succeeded</b> : <div class="sub-desc">\r
150          * The remote-request succeeded but the reader could not read the response.\r
151          * This means the server returned data, but the configured Reader threw an\r
152          * error while reading the response.  In this case, this event will be\r
153          * raised and the caught error will be passed along into this event.\r
154          * </div></li>\r
155          * </ul></div>\r
156          * <br><p>This event fires with two different contexts based upon the 2nd\r
157          * parameter <tt>type [remote|response]</tt>.  The first four parameters\r
158          * are identical between the two contexts -- only the final two parameters\r
159          * differ.</p>\r
160          * @param {DataProxy} this The proxy that sent the request\r
161          * @param {String} type\r
162          * <p>The value of this parameter will be either <tt>'response'</tt> or <tt>'remote'</tt>.</p>\r
163          * <div class="mdetail-params"><ul>\r
164          * <li><b><tt>'response'</tt></b> : <div class="sub-desc">\r
165          * <p>An <b>invalid</b> response from the server was returned: either 404,\r
166          * 500 or the response meta-data does not match that defined in the DataReader\r
167          * (e.g.: root, idProperty, successProperty).</p>\r
168          * </div></li>\r
169          * <li><b><tt>'remote'</tt></b> : <div class="sub-desc">\r
170          * <p>A <b>valid</b> response was returned from the server having\r
171          * successProperty === false.  This response might contain an error-message\r
172          * sent from the server.  For example, the user may have failed\r
173          * authentication/authorization or a database validation error occurred.</p>\r
174          * </div></li>\r
175          * </ul></div>\r
176          * @param {String} action Name of the action (see {@link Ext.data.Api#actions}.\r
177          * @param {Object} options The options for the action that were specified in the {@link #request}.\r
178          * @param {Object} response\r
179          * <p>The value of this parameter depends on the value of the <code>type</code> parameter:</p>\r
180          * <div class="mdetail-params"><ul>\r
181          * <li><b><tt>'response'</tt></b> : <div class="sub-desc">\r
182          * <p>The raw browser response object (e.g.: XMLHttpRequest)</p>\r
183          * </div></li>\r
184          * <li><b><tt>'remote'</tt></b> : <div class="sub-desc">\r
185          * <p>The decoded response object sent from the server.</p>\r
186          * </div></li>\r
187          * </ul></div>\r
188          * @param {Mixed} arg\r
189          * <p>The type and value of this parameter depends on the value of the <code>type</code> parameter:</p>\r
190          * <div class="mdetail-params"><ul>\r
191          * <li><b><tt>'response'</tt></b> : Error<div class="sub-desc">\r
192          * <p>The JavaScript Error object caught if the configured Reader could not read the data.\r
193          * If the remote request returns success===false, this parameter will be null.</p>\r
194          * </div></li>\r
195          * <li><b><tt>'remote'</tt></b> : Record/Record[]<div class="sub-desc">\r
196          * <p>This parameter will only exist if the <tt>action</tt> was a <b>write</b> action\r
197          * (Ext.data.Api.actions.create|update|destroy).</p>\r
198          * </div></li>\r
199          * </ul></div>\r
200          */\r
201         'exception',\r
202         <div id="event-Ext.data.DataProxy-beforeload"></div>/**\r
203          * @event beforeload\r
204          * Fires before a request to retrieve a data object.\r
205          * @param {DataProxy} this The proxy for the request\r
206          * @param {Object} params The params object passed to the {@link #request} function\r
207          */\r
208         'beforeload',\r
209         <div id="event-Ext.data.DataProxy-load"></div>/**\r
210          * @event load\r
211          * Fires before the load method's callback is called.\r
212          * @param {DataProxy} this The proxy for the request\r
213          * @param {Object} o The request transaction object\r
214          * @param {Object} options The callback's <tt>options</tt> property as passed to the {@link #request} function\r
215          */\r
216         'load',\r
217         <div id="event-Ext.data.DataProxy-loadexception"></div>/**\r
218          * @event loadexception\r
219          * <p>This event is <b>deprecated</b>.  The signature of the loadexception event\r
220          * varies depending on the proxy, use the catch-all {@link #exception} event instead.\r
221          * This event will fire in addition to the {@link #exception} event.</p>\r
222          * @param {misc} misc See {@link #exception}.\r
223          * @deprecated\r
224          */\r
225         'loadexception',\r
226         <div id="event-Ext.data.DataProxy-beforewrite"></div>/**\r
227          * @event beforewrite\r
228          * <p>Fires before a request is generated for one of the actions Ext.data.Api.actions.create|update|destroy</p>\r
229          * <p>In addition to being fired through the DataProxy instance that raised the event, this event is also fired\r
230          * through the Ext.data.DataProxy <i>class</i> to allow for centralized processing of beforewrite events from <b>all</b>\r
231          * DataProxies by attaching a listener to the Ext.data.Proxy class itself.</p>\r
232          * @param {DataProxy} this The proxy for the request\r
233          * @param {String} action [Ext.data.Api.actions.create|update|destroy]\r
234          * @param {Record/Array[Record]} rs The Record(s) to create|update|destroy.\r
235          * @param {Object} params The request <code>params</code> object.  Edit <code>params</code> to add parameters to the request.\r
236          */\r
237         'beforewrite',\r
238         <div id="event-Ext.data.DataProxy-write"></div>/**\r
239          * @event write\r
240          * <p>Fires before the request-callback is called</p>\r
241          * <p>In addition to being fired through the DataProxy instance that raised the event, this event is also fired\r
242          * through the Ext.data.DataProxy <i>class</i> to allow for centralized processing of write events from <b>all</b>\r
243          * DataProxies by attaching a listener to the Ext.data.Proxy class itself.</p>\r
244          * @param {DataProxy} this The proxy that sent the request\r
245          * @param {String} action [Ext.data.Api.actions.create|upate|destroy]\r
246          * @param {Object} data The data object extracted from the server-response\r
247          * @param {Object} response The decoded response from server\r
248          * @param {Record/Record{}} rs The records from Store\r
249          * @param {Object} options The callback's <tt>options</tt> property as passed to the {@link #request} function\r
250          */\r
251         'write'\r
252     );\r
253     Ext.data.DataProxy.superclass.constructor.call(this);\r
254 \r
255     // Prepare the proxy api.  Ensures all API-actions are defined with the Object-form.\r
256     try {\r
257         Ext.data.Api.prepare(this);\r
258     } catch (e) {\r
259         if (e instanceof Ext.data.Api.Error) {\r
260             e.toConsole();\r
261         }\r
262     }\r
263     // relay each proxy's events onto Ext.data.DataProxy class for centralized Proxy-listening\r
264     Ext.data.DataProxy.relayEvents(this, ['beforewrite', 'write', 'exception']);\r
265 };\r
266 \r
267 Ext.extend(Ext.data.DataProxy, Ext.util.Observable, {\r
268     <div id="cfg-Ext.data.DataProxy-restful"></div>/**\r
269      * @cfg {Boolean} restful\r
270      * <p>Defaults to <tt>false</tt>.  Set to <tt>true</tt> to operate in a RESTful manner.</p>\r
271      * <br><p> Note: this parameter will automatically be set to <tt>true</tt> if the\r
272      * {@link Ext.data.Store} it is plugged into is set to <code>restful: true</code>. If the\r
273      * Store is RESTful, there is no need to set this option on the proxy.</p>\r
274      * <br><p>RESTful implementations enable the serverside framework to automatically route\r
275      * actions sent to one url based upon the HTTP method, for example:\r
276      * <pre><code>\r
277 store: new Ext.data.Store({\r
278     restful: true,\r
279     proxy: new Ext.data.HttpProxy({url:'/users'}); // all requests sent to /users\r
280     ...\r
281 )}\r
282      * </code></pre>\r
283      * If there is no <code>{@link #api}</code> specified in the configuration of the proxy,\r
284      * all requests will be marshalled to a single RESTful url (/users) so the serverside\r
285      * framework can inspect the HTTP Method and act accordingly:\r
286      * <pre>\r
287 <u>Method</u>   <u>url</u>        <u>action</u>\r
288 POST     /users     create\r
289 GET      /users     read\r
290 PUT      /users/23  update\r
291 DESTROY  /users/23  delete\r
292      * </pre></p>\r
293      * <p>If set to <tt>true</tt>, a {@link Ext.data.Record#phantom non-phantom} record's\r
294      * {@link Ext.data.Record#id id} will be appended to the url. Some MVC (e.g., Ruby on Rails,\r
295      * Merb and Django) support segment based urls where the segments in the URL follow the\r
296      * Model-View-Controller approach:<pre><code>\r
297      * someSite.com/controller/action/id\r
298      * </code></pre>\r
299      * Where the segments in the url are typically:<div class="mdetail-params"><ul>\r
300      * <li>The first segment : represents the controller class that should be invoked.</li>\r
301      * <li>The second segment : represents the class function, or method, that should be called.</li>\r
302      * <li>The third segment : represents the ID (a variable typically passed to the method).</li>\r
303      * </ul></div></p>\r
304      * <br><p>Refer to <code>{@link Ext.data.DataProxy#api}</code> for additional information.</p>\r
305      */\r
306     restful: false,\r
307 \r
308     <div id="method-Ext.data.DataProxy-setApi"></div>/**\r
309      * <p>Redefines the Proxy's API or a single action of an API. Can be called with two method signatures.</p>\r
310      * <p>If called with an object as the only parameter, the object should redefine the <b>entire</b> API, e.g.:</p><pre><code>\r
311 proxy.setApi({\r
312     read    : '/users/read',\r
313     create  : '/users/create',\r
314     update  : '/users/update',\r
315     destroy : '/users/destroy'\r
316 });\r
317 </code></pre>\r
318      * <p>If called with two parameters, the first parameter should be a string specifying the API action to\r
319      * redefine and the second parameter should be the URL (or function if using DirectProxy) to call for that action, e.g.:</p><pre><code>\r
320 proxy.setApi(Ext.data.Api.actions.read, '/users/new_load_url');\r
321 </code></pre>\r
322      * @param {String/Object} api An API specification object, or the name of an action.\r
323      * @param {String/Function} url The URL (or function if using DirectProxy) to call for the action.\r
324      */\r
325     setApi : function() {\r
326         if (arguments.length == 1) {\r
327             var valid = Ext.data.Api.isValid(arguments[0]);\r
328             if (valid === true) {\r
329                 this.api = arguments[0];\r
330             }\r
331             else {\r
332                 throw new Ext.data.Api.Error('invalid', valid);\r
333             }\r
334         }\r
335         else if (arguments.length == 2) {\r
336             if (!Ext.data.Api.isAction(arguments[0])) {\r
337                 throw new Ext.data.Api.Error('invalid', arguments[0]);\r
338             }\r
339             this.api[arguments[0]] = arguments[1];\r
340         }\r
341         Ext.data.Api.prepare(this);\r
342     },\r
343 \r
344     <div id="method-Ext.data.DataProxy-isApiAction"></div>/**\r
345      * Returns true if the specified action is defined as a unique action in the api-config.\r
346      * request.  If all API-actions are routed to unique urls, the xaction parameter is unecessary.  However, if no api is defined\r
347      * and all Proxy actions are routed to DataProxy#url, the server-side will require the xaction parameter to perform a switch to\r
348      * the corresponding code for CRUD action.\r
349      * @param {String [Ext.data.Api.CREATE|READ|UPDATE|DESTROY]} action\r
350      * @return {Boolean}\r
351      */\r
352     isApiAction : function(action) {\r
353         return (this.api[action]) ? true : false;\r
354     },\r
355 \r
356     <div id="method-Ext.data.DataProxy-request"></div>/**\r
357      * All proxy actions are executed through this method.  Automatically fires the "before" + action event\r
358      * @param {String} action Name of the action\r
359      * @param {Ext.data.Record/Ext.data.Record[]/null} rs Will be null when action is 'load'\r
360      * @param {Object} params\r
361      * @param {Ext.data.DataReader} reader\r
362      * @param {Function} callback\r
363      * @param {Object} scope Scope with which to call the callback (defaults to the Proxy object)\r
364      * @param {Object} options Any options specified for the action (e.g. see {@link Ext.data.Store#load}.\r
365      */\r
366     request : function(action, rs, params, reader, callback, scope, options) {\r
367         if (!this.api[action] && !this.load) {\r
368             throw new Ext.data.DataProxy.Error('action-undefined', action);\r
369         }\r
370         params = params || {};\r
371         if ((action === Ext.data.Api.actions.read) ? this.fireEvent("beforeload", this, params) : this.fireEvent("beforewrite", this, action, rs, params) !== false) {\r
372             this.doRequest.apply(this, arguments);\r
373         }\r
374         else {\r
375             callback.call(scope || this, null, options, false);\r
376         }\r
377     },\r
378 \r
379 \r
380     <div id="method-Ext.data.DataProxy-load"></div>/**\r
381      * <b>Deprecated</b> load method using old method signature. See {@doRequest} for preferred method.\r
382      * @deprecated\r
383      * @param {Object} params\r
384      * @param {Object} reader\r
385      * @param {Object} callback\r
386      * @param {Object} scope\r
387      * @param {Object} arg\r
388      */\r
389     load : null,\r
390 \r
391     <div id="cfg-Ext.data.DataProxy-doRequest"></div>/**\r
392      * @cfg {Function} doRequest Abstract method that should be implemented in all subclasses\r
393      * (e.g.: {@link Ext.data.HttpProxy#doRequest HttpProxy.doRequest},\r
394      * {@link Ext.data.DirectProxy#doRequest DirectProxy.doRequest}).\r
395      */\r
396     doRequest : function(action, rs, params, reader, callback, scope, options) {\r
397         // default implementation of doRequest for backwards compatibility with 2.0 proxies.\r
398         // If we're executing here, the action is probably "load".\r
399         // Call with the pre-3.0 method signature.\r
400         this.load(params, reader, callback, scope, options);\r
401     },\r
402 \r
403     /**\r
404      * buildUrl\r
405      * Sets the appropriate url based upon the action being executed.  If restful is true, and only a single record is being acted upon,\r
406      * url will be built Rails-style, as in "/controller/action/32".  restful will aply iff the supplied record is an\r
407      * instance of Ext.data.Record rather than an Array of them.\r
408      * @param {String} action The api action being executed [read|create|update|destroy]\r
409      * @param {Ext.data.Record/Array[Ext.data.Record]} The record or Array of Records being acted upon.\r
410      * @return {String} url\r
411      * @private\r
412      */\r
413     buildUrl : function(action, record) {\r
414         record = record || null;\r
415         var url = (this.api[action]) ? this.api[action].url : this.url;\r
416         if (!url) {\r
417             throw new Ext.data.Api.Error('invalid-url', action);\r
418         }\r
419 \r
420         // look for urls having "provides" suffix (from Rails/Merb and others...),\r
421         // e.g.: /users.json, /users.xml, etc\r
422         // with restful routes, we need urls like:\r
423         // PUT /users/1.json\r
424         // DELETE /users/1.json\r
425         var format = null;\r
426         var m = url.match(/(.*)(\.json|\.xml|\.html)$/);\r
427         if (m) {\r
428             format = m[2];  // eg ".json"\r
429             url = m[1];     // eg: "/users"\r
430         }\r
431         // prettyUrls is deprectated in favor of restful-config\r
432         if ((this.prettyUrls === true || this.restful === true) && record instanceof Ext.data.Record && !record.phantom) {\r
433             url += '/' + record.id;\r
434         }\r
435         if (format) {   // <-- append the request format if exists (ie: /users/update/69[.json])\r
436             url += format;\r
437         }\r
438         return url;\r
439     },\r
440 \r
441     <div id="method-Ext.data.DataProxy-destroy"></div>/**\r
442      * Destroys the proxy by purging any event listeners and cancelling any active requests.\r
443      */\r
444     destroy: function(){\r
445         this.purgeListeners();\r
446     }\r
447 });\r
448 \r
449 // Apply the Observable prototype to the DataProxy class so that proxy instances can relay their\r
450 // events to the class.  Allows for centralized listening of all proxy instances upon the DataProxy class.\r
451 Ext.apply(Ext.data.DataProxy, Ext.util.Observable.prototype);\r
452 Ext.util.Observable.call(Ext.data.DataProxy);\r
453 \r
454 <div id="cls-Ext.data.DataProxy.Error"></div>/**\r
455  * @class Ext.data.DataProxy.Error\r
456  * @extends Ext.Error\r
457  * DataProxy Error extension.\r
458  * constructor\r
459  * @param {String} name\r
460  * @param {Record/Array[Record]/Array}\r
461  */\r
462 Ext.data.DataProxy.Error = Ext.extend(Ext.Error, {\r
463     constructor : function(message, arg) {\r
464         this.arg = arg;\r
465         Ext.Error.call(this, message);\r
466     },\r
467     name: 'Ext.data.DataProxy'\r
468 });\r
469 Ext.apply(Ext.data.DataProxy.Error.prototype, {\r
470     lang: {\r
471         'action-undefined': "DataProxy attempted to execute an API-action but found an undefined url / function.  Please review your Proxy url/api-configuration.",\r
472         'api-invalid': 'Recieved an invalid API-configuration.  Please ensure your proxy API-configuration contains only the actions from Ext.data.Api.actions.'\r
473     }\r
474 });\r
475 \r
476 \r
477 </pre>
478 </body>
479 </html>