]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - jssource/src_files/include/javascript/yui3/build/jsonp/jsonp.js
Release 6.5.0
[Github/sugarcrm.git] / jssource / src_files / include / javascript / yui3 / build / jsonp / jsonp.js
1 /*
2 Copyright (c) 2010, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
5 version: 3.3.0
6 build: 3167
7 */
8 YUI.add('jsonp', function(Y) {
9
10 var isFunction = Y.Lang.isFunction;
11
12 /**
13  * <p>Provides a JSONPRequest class for repeated JSONP calls, and a convenience
14  * method Y.jsonp(url, callback) to instantiate and send a JSONP request.</p>
15  *
16  * <p>Both the constructor as well as the convenience function take two
17  * parameters: a url string and a callback.</p>
18  *
19  * <p>The url provided must include the placeholder string
20  * &quot;{callback}&quot; which will be replaced by a dynamically
21  * generated routing function to pass the data to your callback function.
22  * An example url might look like
23  * &quot;http://example.com/service?callback={callback}&quot;.</p>
24  *
25  * <p>The second parameter can be a callback function that accepts the JSON
26  * payload as its argument, or a configuration object supporting the keys:</p>
27  * <ul>
28  *   <li>on - map of callback subscribers
29  *      <ul>
30  *         <li>success - function handler for successful transmission</li>
31  *         <li>failure - function handler for failed transmission</li>
32  *         <li>timeout - function handler for transactions that timeout</li>
33  *      </ul>
34  *  </li>
35  *  <li>format  - override function for inserting the proxy name in the url</li>
36  *  <li>timeout - the number of milliseconds to wait before giving up</li>
37  *  <li>context - becomes <code>this</code> in the callbacks</li>
38  *  <li>args    - array of subsequent parameters to pass to the callbacks</li>
39  *  <li>allowCache - use the same proxy name for all requests? (boolean)</li>
40  * </ul>
41  *
42  * @module jsonp
43  * @class JSONPRequest
44  * @constructor
45  * @param url {String} the url of the JSONP service
46  * @param callback {Object|Function} the default callback configuration or
47  *                                   success handler
48  */
49 function JSONPRequest() {
50     this._init.apply(this, arguments);
51 }
52
53 JSONPRequest.prototype = {
54     /**
55      * Number of requests currently pending responses.  Used by connections
56      * configured to allowCache to make sure the proxy isn't deleted until
57      * the last response has returned.
58      *
59      * @property _requests
60      * @private
61      * @type {Number}
62      */
63     _requests: 0,
64
65     /**
66      * Set up the success and failure handlers and the regex pattern used
67      * to insert the temporary callback name in the url.
68      *
69      * @method _init
70      * @param url {String} the url of the JSONP service
71      * @param callback {Object|Function} Optional success callback or config
72      *                  object containing success and failure functions and
73      *                  the url regex.
74      * @protected
75      */
76     _init : function (url, callback) {
77         this.url = url;
78
79         // Accept a function, an object, or nothing
80         callback = (isFunction(callback)) ?
81             { on: { success: callback } } :
82             callback || {};
83
84         var subs = callback.on || {};
85
86         if (!subs.success) {
87             subs.success = this._defaultCallback(url, callback);
88         }
89
90         // Apply defaults and store
91         this._config = Y.merge({
92                 context: this,
93                 args   : [],
94                 format : this._format,
95                 allowCache: false
96             }, callback, { on: subs });
97     },
98
99     /** 
100      * Override this method to provide logic to default the success callback if
101      * it is not provided at construction.  This is overridden by jsonp-url to
102      * parse the callback from the url string.
103      * 
104      * @method _defaultCallback
105      * @param url {String} the url passed at construction
106      * @param config {Object} (optional) the config object passed at
107      *                        construction
108      * @return {Function}
109      */
110     _defaultCallback: function () {},
111
112     /** 
113      * Issues the JSONP request.
114      *
115      * @method send
116      * @param args* {any} any additional arguments to pass to the url formatter
117      *              beyond the base url and the proxy function name
118      * @chainable
119      */
120     send : function () {
121         var self   = this,
122             args   = Y.Array(arguments, 0, true),
123             config = self._config,
124             proxy  = self._proxy || Y.guid(),
125             url;
126             
127         // TODO: support allowCache as time value
128         if (config.allowCache) {
129             self._proxy = proxy;
130
131             // In case additional requests are issued before the current request
132             // returns, don't remove the proxy.
133             self._requests++;
134         }
135
136         args.unshift(self.url, 'YUI.Env.JSONP.' + proxy);
137         url = config.format.apply(self, args);
138
139         if (!config.on.success) {
140             return self;
141         }
142
143         function wrap(fn) {
144             return (isFunction(fn)) ?
145                 function (data) {
146                     if (!config.allowCache || !--self._requests) {
147                         delete YUI.Env.JSONP[proxy];
148                     }
149                     fn.apply(config.context, [data].concat(config.args));
150                 } :
151                 null;
152         }
153
154         // Temporary un-sandboxed function alias
155         // TODO: queuing
156         YUI.Env.JSONP[proxy] = wrap(config.on.success);
157
158         Y.Get.script(url, {
159             onFailure: wrap(config.on.failure),
160             onTimeout: wrap(config.on.timeout),
161             timeout  : config.timeout
162         });
163
164         return self;
165     },
166
167     /**
168      * Default url formatter.  Looks for callback= in the url and appends it
169      * if not present.  The supplied proxy name will be assigned to the query
170      * param.  Override this method by passing a function as the
171      * &quot;format&quot; property in the config object to the constructor.
172      *
173      * @method _format
174      * @param url { String } the original url
175      * @param proxy {String} the function name that will be used as a proxy to
176      *      the configured callback methods.
177      * @param args* {any} additional args passed to send()
178      * @return {String} fully qualified JSONP url
179      * @protected
180      */
181     _format: function (url, proxy) {
182         return url.replace(/\{callback\}/, proxy);
183     }
184 };
185
186 Y.JSONPRequest = JSONPRequest;
187
188 /**
189  *
190  * @method Y.jsonp
191  * @param url {String} the url of the JSONP service with the {callback}
192  *          placeholder where the callback function name typically goes.
193  * @param c {Function|Object} Callback function accepting the JSON payload
194  *          as its argument, or a configuration object (see above).
195  * @param args* {any} additional arguments to pass to send()
196  * @return {JSONPRequest}
197  * @static
198  */
199 Y.jsonp = function (url,c) {
200     var req = new Y.JSONPRequest(url,c);
201     return req.send.apply(req, Y.Array(arguments, 2, true));
202 };
203
204 if (!YUI.Env.JSONP) {
205     YUI.Env.JSONP = {};
206 }
207
208
209 }, '3.3.0' ,{requires:['get','oop']});