2 Copyright (c) 2009, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
8 YUI.add('io-base', function(Y) {
11 * Base IO functionality. Provides basic XHR transport support.
17 * The io class is a utility that brokers HTTP requests through a simplified
18 * interface. Specifically, it allows JavaScript to make HTTP requests to
19 * a resource without a page reload. The underlying transport for making
20 * same-domain requests is the XMLHttpRequest object. YUI.io can also use
21 * Flash, if specified as a transport, for cross-domain requests.
28 * @description This event is fired by YUI.io when a transaction is initiated.
31 var E_START = 'io:start',
35 * @description This event is fired by YUI.io when a transaction is complete.
36 * Response status and data are accessible, if available.
39 E_COMPLETE = 'io:complete',
43 * @description This event is fired by YUI.io when a transaction is complete, and
44 * the HTTP status resolves to HTTP2xx.
47 E_SUCCESS = 'io:success',
51 * @description This event is fired by YUI.io when a transaction is complete, and
52 * the HTTP status resolves to HTTP4xx, 5xx and above.
55 E_FAILURE = 'io:failure',
59 * @description This event signifies the end of the transaction lifecycle. The
60 * transaction transport is destroyed.
65 //--------------------------------------
67 //--------------------------------------
69 * @description A transaction counter that increments for each transaction.
71 * @property transactionId
79 * @description Object of default HTTP headers to be initialized and sent
80 * for all transactions.
88 'X-Requested-With' : 'XMLHttpRequest'
92 * @description Object that stores timeout values for any transaction with
93 * a defined "timeout" configuration property.
105 //--------------------------------------
107 //--------------------------------------
109 * @description Method for requesting a transaction. _io() is implemented as
110 * yui.io(). Each transaction may include a configuration object. Its
113 * method: HTTP method verb (e.g., GET or POST). If this property is not
114 * not defined, the default value will be GET.
116 * data: This is the name-value string that will be sent as the transaction
117 * data. If the request is HTTP GET, the data become part of
118 * querystring. If HTTP POST, the data are sent in the message body.
120 * xdr: Defines the transport to be used for cross-domain requests. By
121 * setting this property, the transaction will use the specified
122 * transport instead of XMLHttpRequest. Currently, the only alternate
123 * transport supported is Flash (e.g., { xdr: 'flash' }).
125 * form: This is a defined object used to process HTML form as data. The
128 * id: object, //HTML form object or id of HTML form
129 * useDisabled: boolean, //Allow disabled HTML form field values
130 * to be sent as part of the data.
133 * on: This is a defined object used to create and handle specific
134 * events during a transaction lifecycle. These events will fire in
135 * addition to the global io events. The events are:
136 * start - This event is fired when a request is sent to a resource.
137 * complete - This event fires when the transaction is complete.
138 * success - This event fires when the response status resolves to
140 * failure - This event fires when the response status resolves to
141 * HTTP 4xx, 5xx; and, for all transaction exceptions,
142 * including aborted transactions and transaction timeouts.
143 * end - This even is fired at the conclusion of the transaction
144 * lifecycle, after a success or failure resolution.
146 * The properties are:
148 * start: function(id, args){},
149 * complete: function(id, responseobject, args){},
150 * success: function(id, responseobject, args){},
151 * failure: function(id, responseobject, args){},
152 * end: function(id, args){}
154 * Each property can reference a function or be written as an
157 * context: Object reference for an event handler when it is implemented
158 * as a method of a base object. Defining "context" will preserve
159 * the proper reference of "this" used in the event handler.
160 * headers: This is a defined object of client headers, as many as.
161 * desired for the transaction. These headers are sentThe object
167 * timeout: This value, defined as milliseconds, is a time threshold for the
168 * transaction. When this threshold is reached, and the transaction's
169 * Complete event has not yet fired, the transaction will be aborted.
170 * arguments: Object, array, string, or number passed to all registered
171 * event handlers. This value is available as the second
172 * argument in the "start" and "abort" event handlers; and, it is
173 * the third argument in the "complete", "success", and "failure"
179 * @param {string} uri - qualified path to transaction resource.
180 * @param {object} c - configuration object for the transaction.
181 * @param {number} i - transaction id, if already set by queue.
184 function _io(uri, c, i) {
187 o = _create(c.xdr || c.form, i);
188 m = c.method ? c.method.toUpperCase() : 'GET';
192 return Y.io._upload(o, uri, c);
195 f = Y.io._serialize(c.form, c.data);
198 _setHeader('Content-Type', 'application/x-www-form-urlencoded');
200 else if (m === 'GET') {
201 uri = _concat(uri, f);
205 else if (c.data && m === 'GET') {
206 uri = _concat(uri, c.data);
210 if (c.xdr.use === 'native' && window.XDomainRequest || c.xdr.use === 'flash') {
211 return Y.io.xdr(uri, o, c);
213 if (c.xdr.credentials) {
214 o.c.withCredentials = true;
218 o.c.onreadystatechange = function() { _readyState(o, c); };
220 o.c.open(m, uri, true);
224 // This exception is usually thrown by browsers
225 // that do not support native XDR transactions.
226 return _resend(o, uri, c);
230 if (c.data && m === 'POST') {
231 _setHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
234 _setHeaders(o.c, c.headers || {});
236 // Using "null" will result in a POST request with
237 // no Content-Length defined.
238 o.c.send(c.data || '');
242 // This exception is usually thrown by browsers
243 // that do not support native XDR transactions.
244 return _resend(o, uri, c);
249 // If config.timeout is defined, and the request is standard XHR,
250 // initialize timeout polling.
252 _startTimeout(o, c.timeout);
258 return o.c ? _ioCancel(o, 'abort') : false;
260 isInProgress: function() {
261 return o.c ? o.c.readyState !== 4 && o.c.readyState !== 0 : false;
267 * @description Method for creating and subscribing transaction events.
272 * @param {string} e - event to be published
273 * @param {object} c - configuration data subset for event subscription.
277 function _subscribe(e, c){
278 var evt = new Y.EventTarget().publish('transaction:' + e);
279 evt.subscribe(c.on[e], (c.context || Y), c.arguments);
285 * @description Fires event "io:start" and creates, fires a
286 * transaction-specific start event, if config.on.start is
292 * @param {number} id - transaction id
293 * @param {object} c - configuration object for the transaction.
297 function _ioStart(id, c) {
299 // Set default value of argument c, property "on" to Object if
300 // the property is null or undefined.
305 evt = _subscribe('start', c);
312 * @description Fires event "io:complete" and creates, fires a
313 * transaction-specific "complete" event, if config.on.complete is
316 * @method _ioComplete
319 * @param {object} o - transaction object.
320 * @param {object} c - configuration object for the transaction.
324 function _ioComplete(o, c) {
326 r = o.status ? { status: 0, statusText: o.status } : o.c;
327 // Set default value of argument c, property "on" to Object if
328 // the property is null or undefined.
331 Y.fire(E_COMPLETE, o.id, r);
333 evt = _subscribe('complete', c);
339 * @description Fires event "io:success" and creates, fires a
340 * transaction-specific "success" event, if config.on.success is
346 * @param {object} o - transaction object.
347 * @param {object} c - configuration object for the transaction.
351 function _ioSuccess(o, c) {
353 // Set default value of argument c, property "on" to Object if
354 // the property is null or undefined.
357 Y.fire(E_SUCCESS, o.id, o.c);
359 evt = _subscribe('success', c);
367 * @description Fires event "io:failure" and creates, fires a
368 * transaction-specific "failure" event, if config.on.failure is
374 * @param {object} o - transaction object.
375 * @param {object} c - configuration object for the transaction.
379 function _ioFailure(o, c) {
381 r = o.status ? { status: 0, statusText: o.status } : o.c;
382 // Set default value of argument c, property "on" to Object if
383 // the property is null or undefined.
386 Y.fire(E_FAILURE, o.id, r);
388 evt = _subscribe('failure', c);
396 * @description Fires event "io:end" and creates, fires a
397 * transaction-specific "end" event, if config.on.end is
403 * @param {object} o - transaction object.
404 * @param {object} c - configuration object for the transaction.
408 function _ioEnd(o, c) {
410 // Set default value of argument c, property "on" to Object if
411 // the property is null or undefined.
416 evt = _subscribe('end', c);
420 _destroy(o, c.xdr ? true : false );
424 * @description Terminates a transaction due to an explicit abort or
430 * @param {object} o - Transaction object generated by _create().
431 * @param {string} s - Identifies timed out or aborted transaction.
435 function _ioCancel(o, s) {
443 * @description Resends an XDR transaction, using the Flash tranport,
444 * if the native transport fails.
450 * @param {object} o - Transaction object generated by _create().
451 * @param {string} uri - qualified path to transaction resource.
452 * @param {object} c - configuration object for the transaction.
456 function _resend(o, uri, c) {
457 var id = parseInt(o.id);
462 return Y.io(uri, c, id);
466 * @description Method that increments _transactionId for each transaction.
474 var id = transactionId;
482 * @description Method that creates a unique transaction object for each
488 * @param {number} c - configuration object subset to determine if
489 * the transaction is an XDR or file upload,
490 * requiring an alternate transport.
491 * @param {number} i - transaction id
494 function _create(c, i) {
496 o.id = Y.Lang.isNumber(i) ? i : _id();
499 if (!c.use && !c.upload) {
503 if (c.use === 'flash') {
504 o.c = Y.io._transport[c.use];
506 else if (c.use === 'native' && window.XDomainRequest) {
507 o.c = new XDomainRequest();
521 * @description Method that creates the XMLHttpRequest transport
529 return w.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
533 * @description Method that concatenates string data for HTTP GET transactions.
538 * @param {string} s - URI or root data.
539 * @param {string} d - data to be concatenated onto URI.
542 function _concat(s, d) {
543 s += ((s.indexOf('?') == -1) ? '?' : '&') + d;
548 * @description Method that stores default client headers for all transactions.
549 * If a label is passed with no value argument, the header will be deleted.
554 * @param {string} l - HTTP header
555 * @param {string} v - HTTP header value
558 function _setHeader(l, v) {
568 * @description Method that sets all HTTP headers to be sent in a transaction.
570 * @method _setHeaders
573 * @param {object} o - XHR instance for the specific transaction.
574 * @param {object} h - HTTP headers for the specific transaction, as defined
575 * in the configuration object passed to YUI.io().
578 function _setHeaders(o, h) {
581 for (p in _headers) {
582 if (_headers.hasOwnProperty(p)) {
584 // Configuration headers will supersede IO preset headers,
595 if (h.hasOwnProperty(p)) {
596 o.setRequestHeader(p, h[p]);
602 * @description Starts timeout count if the configuration object
603 * has a defined timeout property.
605 * @method _startTimeout
608 * @param {object} o - Transaction object generated by _create().
609 * @param {object} c - Configuration object passed to YUI.io().
612 function _startTimeout(o, timeout) {
613 _timeout[o.id] = w.setTimeout(function() { _ioCancel(o, 'timeout'); }, timeout);
617 * @description Clears the timeout interval started by _startTimeout().
619 * @method _clearTimeout
622 * @param {number} id - Transaction id.
625 function _clearTimeout(id) {
626 w.clearTimeout(_timeout[id]);
631 * @description Event handler bound to onreadystatechange.
633 * @method _readyState
636 * @param {object} o - Transaction object generated by _create().
637 * @param {object} c - Configuration object passed to YUI.io().
640 function _readyState(o, c) {
641 if (o.c.readyState === 4) {
649 _handleResponse(o, c);
655 * @description Method that determines if a transaction response qualifies
656 * as success or failure, based on the response HTTP status code, and
657 * fires the appropriate success or failure events.
659 * @method _handleResponse
662 * @param {object} o - Transaction object generated by _create().
663 * @param {object} c - Configuration object passed to io().
666 function _handleResponse(o, c) {
669 if (o.c.status && o.c.status !== 0) {
680 // IE reports HTTP 204 as HTTP 1223.
681 if (status >= 200 && status < 300 || status === 1223) {
689 function _destroy(o, transport) {
690 // IE, when using XMLHttpRequest as an ActiveX Object, will throw
691 // a "Type Mismatch" error if the event handler is set to "null".
692 if(w.XMLHttpRequest && !transport) {
694 o.c.onreadystatechange = null;
702 _io.start = _ioStart;
703 _io.complete = _ioComplete;
704 _io.success = _ioSuccess;
705 _io.failure = _ioFailure;
708 _io._timeout = _timeout;
710 //--------------------------------------
711 // Begin public interface definition
712 //--------------------------------------
714 * @description Method that stores default client headers for all transactions.
715 * If a label is passed with no value argument, the header will be deleted.
716 * This is the interface for _setHeader().
721 * @param {string} l - HTTP header
722 * @param {string} v - HTTP header value
725 _io.header = _setHeader;
728 * @description Method for requesting a transaction. This
729 * is the interface for _io().
734 * @param {string} uri - qualified path to transaction resource.
735 * @param {object} c - configuration object for the transaction.
743 }, '3.0.0' ,{requires:['event-custom-base']});