Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
YUI.add('jsonp', function (Y, NAME) {
2
 
3
/*jslint maxlen: 350 */
4
var isFunction = Y.Lang.isFunction;
5
 
6
/**
7
 * <p>Provides a JSONPRequest class for repeated JSONP calls, and a convenience
8
 * method Y.jsonp(url, callback) to instantiate and send a JSONP request.</p>
9
 *
10
 * <p>Both the constructor as well as the convenience function take two
11
 * parameters: a url string and a callback.</p>
12
 *
13
 * <p>The url provided must include the placeholder string
14
 * &quot;{callback}&quot; which will be replaced by a dynamically
15
 * generated routing function to pass the data to your callback function.
16
 * An example url might look like
17
 * &quot;http://example.com/service?callback={callback}&quot;.</p>
18
 *
19
 * <p>The second parameter can be a callback function that accepts the JSON
20
 * payload as its argument, or a configuration object supporting the keys:</p>
21
 * <ul>
22
 *   <li>on - map of callback subscribers
23
 *      <ul>
24
 *         <li>success - function handler for successful transmission</li>
25
 *         <li>failure - function handler for failed transmission</li>
26
 *         <li>timeout - function handler for transactions that timeout</li>
27
 *      </ul>
28
 *  </li>
29
 *  <li>format  - override function for inserting the proxy name in the url</li>
30
 *  <li>timeout - the number of milliseconds to wait before giving up</li>
31
 *  <li>context - becomes <code>this</code> in the callbacks</li>
32
 *  <li>args    - array of subsequent parameters to pass to the callbacks</li>
33
 *  <li>allowCache - use the same proxy name for all requests? (boolean)</li>
34
 * </ul>
35
 *
36
 * @module jsonp
37
 * @class JSONPRequest
38
 * @constructor
39
 * @param url {String} the url of the JSONP service
40
 * @param callback {Object|Function} the default callback configuration or
41
 *                                   success handler
42
 */
43
function JSONPRequest() {
44
    this._init.apply(this, arguments);
45
}
46
 
47
JSONPRequest.prototype = {
48
    /**
49
     * Set up the success and failure handlers and the regex pattern used
50
     * to insert the temporary callback name in the url.
51
     *
52
     * @method _init
53
     * @param url {String} the url of the JSONP service
54
     * @param callback {Object|Function} Optional success callback or config
55
     *                  object containing success and failure functions and
56
     *                  the url regex.
57
     * @protected
58
     */
59
    _init : function (url, callback) {
60
        this.url = url;
61
 
62
        /**
63
         * Map of the number of requests currently pending responses per
64
         * generated proxy.  Used to ensure the proxy is not flushed if the
65
         * request times out and there is a timeout handler and success
66
         * handler, and used by connections configured to allowCache to make
67
         * sure the proxy isn't deleted until the last response has returned.
68
         *
69
         * @property _requests
70
         * @private
71
         * @type {Object}
72
         */
73
        this._requests = {};
74
 
75
        /**
76
         * Map of the number of timeouts received from the destination url
77
         * by generated proxy.  Used to ensure the proxy is not flushed if the
78
         * request times out and there is a timeout handler and success
79
         * handler, and used by connections configured to allowCache to make
80
         * sure the proxy isn't deleted until the last response has returned.
81
         *
82
         * @property _timeouts
83
         * @private
84
         * @type {Object}
85
         */
86
        this._timeouts = {};
87
 
88
        this._failures = {};
89
 
90
        // Accept a function, an object, or nothing
91
        callback = (isFunction(callback)) ?
92
            { on: { success: callback } } :
93
            callback || {};
94
 
95
        var subs = callback.on || {};
96
 
97
        if (!subs.success) {
98
            subs.success = this._defaultCallback(url, callback);
99
        }
100
 
101
        // Apply defaults and store
102
        this._config = Y.merge({
103
                context: this,
104
                args   : [],
105
                format : this._format,
106
                allowCache: false
107
            }, callback, { on: subs });
108
    },
109
 
110
    /**
111
     * Override this method to provide logic to default the success callback if
112
     * it is not provided at construction.  This is overridden by jsonp-url to
113
     * parse the callback from the url string.
114
     *
115
     * @method _defaultCallback
116
     * @param url {String} the url passed at construction
117
     * @param config {Object} (optional) the config object passed at
118
     *                        construction
119
     * @return {Function}
120
     */
121
    _defaultCallback: function () {},
122
 
123
    /**
124
     * Issues the JSONP request.
125
     *
126
     * @method send
127
     * @param args* {any} any additional arguments to pass to the url formatter
128
     *              beyond the base url and the proxy function name
129
     * @chainable
130
     */
131
    send : function () {
132
        var self   = this,
133
            args   = Y.Array(arguments, 0, true),
134
            config = self._config,
135
            proxy  = self._proxy || Y.guid(),
136
            url;
137
 
138
        // TODO: support allowCache as time value
139
        if (config.allowCache) {
140
            self._proxy = proxy;
141
        }
142
 
143
        if (self._requests[proxy] === undefined) {
144
            self._requests[proxy] = 0;
145
        }
146
        if (self._timeouts[proxy] === undefined) {
147
            self._timeouts[proxy] = 0;
148
        }
149
        if (self._failures[proxy] === undefined) {
150
            self._failures[proxy] = 0;
151
        }
152
        self._requests[proxy]++;
153
 
154
 
155
        args.unshift(self.url, 'YUI.Env.JSONP.' + proxy);
156
        url = config.format.apply(self, args);
157
 
158
        if (!config.on.success) {
159
            return self;
160
        }
161
 
162
        function wrap(fn, isTimeout, isFailure) {
163
            return (isFunction(fn)) ?
164
                function (data) {
165
                    var execute = true,
166
                        counter = '_requests';
167
 
168
                    //if (config.allowCache) {
169
                        // A lot of wrangling to make sure timeouts result in
170
                        // fewer success callbacks, but the proxy is properly
171
                        // cleaned up.
172
                        if (isTimeout) {
173
                            ++self._timeouts[proxy];
174
                            --self._requests[proxy];
175
                        } else if (isFailure) {
176
                            ++self._failures[proxy];
177
                            if (self._timeouts[proxy] > 0) {
178
                                --self._timeouts[proxy];
179
                            } else {
180
                                --self._requests[proxy];
181
                            }
182
                        } else {
183
                            if (!self._requests[proxy]) {
184
                                execute = false;
185
                                if (self._timeouts[proxy] > 0) {
186
                                    counter = '_timeouts';
187
                                } else if (self._failures[proxy] > 0) {
188
                                    counter = '_failures';
189
                                }
190
                            }
191
                            --self[counter][proxy];
192
                        }
193
                    //}
194
 
195
                    if (!self._requests[proxy] && !self._timeouts[proxy] && !self._failures[proxy]) {
196
                        delete YUI.Env.JSONP[proxy];
197
                    }
198
 
199
                    if (execute) {
200
                        fn.apply(config.context, [data].concat(config.args));
201
                    }
202
                } :
203
                null;
204
        }
205
 
206
        // Temporary un-sandboxed function alias
207
        // TODO: queuing
208
        YUI.Env.JSONP[proxy] = wrap(config.on.success);
209
 
210
        // Y.Get transactions block each other by design, but can easily
211
        //  be made non-blocking by just calling execute() on the transaction.
212
        // https://github.com/yui/yui3/pull/393#issuecomment-11961608
213
        Y.Get.js(url, {
214
            onFailure : wrap(config.on.failure, false, true),
215
            onTimeout : wrap(config.on.timeout, true, false),
216
            timeout   : config.timeout,
217
            charset   : config.charset,
218
            attributes: config.attributes,
219
            async     : config.async
220
        }).execute();
221
 
222
        return self;
223
    },
224
 
225
    /**
226
     * Default url formatter.  Looks for callback= in the url and appends it
227
     * if not present.  The supplied proxy name will be assigned to the query
228
     * param.  Override this method by passing a function as the
229
     * &quot;format&quot; property in the config object to the constructor.
230
     *
231
     * @method _format
232
     * @param url { String } the original url
233
     * @param proxy {String} the function name that will be used as a proxy to
234
     *      the configured callback methods.
235
     * @param args* {any} additional args passed to send()
236
     * @return {String} fully qualified JSONP url
237
     * @protected
238
     */
239
    _format: function (url, proxy) {
240
        return url.replace(/\{callback\}/, proxy);
241
    }
242
};
243
 
244
Y.JSONPRequest = JSONPRequest;
245
 
246
/**
247
 *
248
 * @method jsonp
249
 * @param url {String} the url of the JSONP service with the {callback}
250
 *          placeholder where the callback function name typically goes.
251
 * @param c {Function|Object} Callback function accepting the JSON payload
252
 *          as its argument, or a configuration object (see above).
253
 * @param args* {any} additional arguments to pass to send()
254
 * @return {JSONPRequest}
255
 * @static
256
 * @for YUI
257
 */
258
Y.jsonp = function (url,c) {
259
    var req = new Y.JSONPRequest(url,c);
260
    return req.send.apply(req, Y.Array(arguments, 2, true));
261
};
262
 
263
if (!YUI.Env.JSONP) {
264
    YUI.Env.JSONP = {};
265
}
266
 
267
 
268
}, '3.18.1', {"requires": ["get", "oop"]});