2 Copyright (c) 2010, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
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 //--------------------------------------
110 * @description Method that creates the XMLHttpRequest transport
118 return w.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
123 * @description Method that increments _transactionId for each transaction.
131 var id = transactionId;
139 * @description Method that creates a unique transaction object for each
145 * @param {number} c - configuration object subset to determine if
146 * the transaction is an XDR or file upload,
147 * requiring an alternate transport.
148 * @param {number} i - transaction id
151 function _create(c, i) {
153 o.id = Y.Lang.isNumber(i) ? i : _id();
156 if (!c.use && !c.upload) {
160 if (c.use === 'native') {
161 if (w.XDomainRequest) {
162 o.c = new XDomainRequest();
170 o.c = Y.io._transport[c.use];
183 function _destroy(o) {
185 if (o.c && w.XMLHttpRequest) {
186 o.c.onreadystatechange = null;
188 else if (Y.UA.ie === 6 && !o.t) {
189 // IE, when using XMLHttpRequest as an ActiveX Object, will throw
190 // a "Type Mismatch" error if the event handler is set to "null".
200 * @description Method for creating and subscribing transaction events.
205 * @param {string} e - event to be published
206 * @param {object} c - configuration data subset for event subscription.
211 var eT = new Y.EventTarget().publish('transaction:' + e),
216 eT.on(c.on[e], cT, a);
226 * @description Fires event "io:start" and creates, fires a
227 * transaction-specific start event, if config.on.start is
233 * @param {number} id - transaction id
234 * @param {object} c - configuration object for the transaction.
238 function _ioStart(id, c) {
242 Y.fire(E_START, id, a);
248 if (c.on && c.on.start) {
249 _tE('start', c).fire(id);
255 * @description Fires event "io:complete" and creates, fires a
256 * transaction-specific "complete" event, if config.on.complete is
259 * @method _ioComplete
262 * @param {object} o - transaction object.
263 * @param {object} c - configuration object for the transaction.
267 function _ioComplete(o, c) {
268 var r = o.e ? { status: 0, statusText: o.e } : o.c,
272 Y.fire(E_COMPLETE, o.id, r, a);
275 Y.fire(E_COMPLETE, o.id, r);
278 if (c.on && c.on.complete) {
279 _tE('complete', c).fire(o.id, r);
284 * @description Fires event "io:end" and creates, fires a
285 * transaction-specific "end" event, if config.on.end is
291 * @param {object} o - transaction object.
292 * @param {object} c - configuration object for the transaction.
296 function _ioEnd(o, c) {
300 Y.fire(E_END, o.id, a);
306 if (c.on && c.on.end) {
307 _tE('end', c).fire(o.id);
314 * @description Fires event "io:success" and creates, fires a
315 * transaction-specific "success" event, if config.on.success is
321 * @param {object} o - transaction object.
322 * @param {object} c - configuration object for the transaction.
326 function _ioSuccess(o, c) {
330 Y.fire(E_SUCCESS, o.id, o.c, a);
333 Y.fire(E_SUCCESS, o.id, o.c);
336 if (c.on && c.on.success) {
337 _tE('success', c).fire(o.id, o.c);
344 * @description Fires event "io:failure" and creates, fires a
345 * transaction-specific "failure" event, if config.on.failure is
351 * @param {object} o - transaction object.
352 * @param {object} c - configuration object for the transaction.
356 function _ioFailure(o, c) {
357 var r = o.e ? { status: 0, statusText: o.e } : o.c,
361 Y.fire(E_FAILURE, o.id, r, a);
364 Y.fire(E_FAILURE, o.id, r);
367 if (c.on && c.on.failure) {
368 _tE('failure', c).fire(o.id, r);
375 * @description Resends an XDR transaction, using the Flash tranport,
376 * if the native transport fails.
382 * @param {object} o - Transaction object generated by _create().
383 * @param {string} uri - qualified path to transaction resource.
384 * @param {object} c - configuration object for the transaction.
388 function _resend(o, uri, c, d) {
391 // If the original request included serialized form data and
392 // additional data are defined in configuration.data, it must
393 // be reset to prevent data duplication.
394 c.data = c.form && d ? d : null;
396 return Y.io(uri, c, o.id);
400 * @description Method that concatenates string data for HTTP GET transactions.
405 * @param {string} s - URI or root data.
406 * @param {string} d - data to be concatenated onto URI.
409 function _concat(s, d) {
410 s += ((s.indexOf('?') == -1) ? '?' : '&') + d;
415 * @description Method that stores default client headers for all transactions.
416 * If a label is passed with no value argument, the header will be deleted.
421 * @param {string} l - HTTP header
422 * @param {string} v - HTTP header value
425 function _setHeader(l, v) {
435 * @description Method that sets all HTTP headers to be sent in a transaction.
437 * @method _setHeaders
440 * @param {object} o - XHR instance for the specific transaction.
441 * @param {object} h - HTTP headers for the specific transaction, as defined
442 * in the configuration object passed to YUI.io().
445 function _setHeaders(o, h) {
449 for (p in _headers) {
450 if (_headers.hasOwnProperty(p)) {
453 // Configuration headers will supersede preset io headers,
468 if (h.hasOwnProperty(p)) {
469 if (h[p] !== 'disable') {
470 o.setRequestHeader(p, h[p]);
477 * @description Terminates a transaction due to an explicit abort or
483 * @param {object} o - Transaction object generated by _create().
484 * @param {string} s - Identifies timed out or aborted transaction.
488 function _ioCancel(o, s) {
496 * @description Starts timeout count if the configuration object
497 * has a defined timeout property.
499 * @method _startTimeout
502 * @param {object} o - Transaction object generated by _create().
503 * @param {object} t - Timeout in milliseconds.
506 function _startTimeout(o, t) {
507 _timeout[o.id] = w.setTimeout(function() { _ioCancel(o, 'timeout'); }, t);
511 * @description Clears the timeout interval started by _startTimeout().
513 * @method _clearTimeout
516 * @param {number} id - Transaction id.
519 function _clearTimeout(id) {
520 w.clearTimeout(_timeout[id]);
525 * @description Method that determines if a transaction response qualifies
526 * as success or failure, based on the response HTTP status code, and
527 * fires the appropriate success or failure events.
529 * @method _handleResponse
532 * @param {object} o - Transaction object generated by _create().
533 * @param {object} c - Configuration object passed to io().
536 function _handleResponse(o, c) {
540 status = (o.c.status && o.c.status !== 0) ? o.c.status : 0;
546 // IE reports HTTP 204 as HTTP 1223.
547 if (status >= 200 && status < 300 || status === 1223) {
556 * @description Event handler bound to onreadystatechange.
558 * @method _readyState
561 * @param {object} o - Transaction object generated by _create().
562 * @param {object} c - Configuration object passed to YUI.io().
565 function _readyState(o, c) {
566 if (o.c.readyState === 4) {
574 _handleResponse(o, c);
580 * @description Method for requesting a transaction. _io() is implemented as
581 * yui.io(). Each transaction may include a configuration object. Its
584 * method: HTTP method verb (e.g., GET or POST). If this property is not
585 * not defined, the default value will be GET.
587 * data: This is the name-value string that will be sent as the transaction
588 * data. If the request is HTTP GET, the data become part of
589 * querystring. If HTTP POST, the data are sent in the message body.
591 * xdr: Defines the transport to be used for cross-domain requests. By
592 * setting this property, the transaction will use the specified
593 * transport instead of XMLHttpRequest.
594 * The properties are:
596 * use: Specify the transport to be used: 'flash' and 'native'
597 * dataType: Set the value to 'XML' if that is the expected
598 * response content type.
602 * form: This is a defined object used to process HTML form as data. The
605 * id: Node object or id of HTML form.
606 * useDisabled: Boolean value to allow disabled HTML form field
607 * values to be sent as part of the data.
610 * on: This is a defined object used to create and handle specific
611 * events during a transaction lifecycle. These events will fire in
612 * addition to the global io events. The events are:
613 * start - This event is fired when a request is sent to a resource.
614 * complete - This event fires when the transaction is complete.
615 * success - This event fires when the response status resolves to
617 * failure - This event fires when the response status resolves to
618 * HTTP 4xx, 5xx; and, for all transaction exceptions,
619 * including aborted transactions and transaction timeouts.
620 * end - This even is fired at the conclusion of the transaction
621 * lifecycle, after a success or failure resolution.
623 * The properties are:
625 * start: function(id, arguments){},
626 * complete: function(id, responseobject, arguments){},
627 * success: function(id, responseobject, arguments){},
628 * failure: function(id, responseobject, arguments){},
629 * end: function(id, arguments){}
631 * Each property can reference a function or be written as an
634 * sync: To enable synchronous transactions, set the configuration property
635 * "sync" to true; the default behavior is false. Synchronous
636 * transactions are limited to same-domain requests only.
638 * context: Object reference for all defined transaction event handlers
639 * when it is implemented as a method of a base object. Defining
640 * "context" will set the reference of "this," used in the
641 * event handlers, to the context value. In the case where
642 * different event handlers all have different contexts,
643 * use Y.bind() to set the execution context, bypassing this
646 * headers: This is a defined object of client headers, as many as.
647 * desired for the transaction. The object pattern is:
648 * { 'header': 'value' }.
650 * timeout: This value, defined as milliseconds, is a time threshold for the
651 * transaction. When this threshold is reached, and the transaction's
652 * Complete event has not yet fired, the transaction will be aborted.
654 * arguments: Object, array, string, or number passed to all registered
655 * event handlers. This value is available as the second
656 * argument in the "start" and "abort" event handlers; and, it is
657 * the third argument in the "complete", "success", and "failure"
663 * @param {string} uri - qualified path to transaction resource.
664 * @param {object} c - configuration object for the transaction.
665 * @param {number} i - transaction id, if already set.
668 function _io(uri, c, i) {
669 var f, o, d, m, r, s, oD, a, j,
672 o = _create(c.xdr || c.form, i);
673 m = c.method ? c.method = c.method.toUpperCase() : c.method = 'GET';
677 //To serialize an object into a key-value string, add the
678 //QueryString module to the YUI instance's 'use' method.
679 if (Y.Lang.isObject(c.data) && Y.QueryString) {
680 c.data = Y.QueryString.stringify(c.data);
685 // This is a file upload transaction, calling
686 // upload() in io-upload-iframe.
687 return Y.io.upload(o, uri, c);
690 // Serialize HTML form data.
691 f = Y.io._serialize(c.form, c.data);
692 if (m === 'POST' || m === 'PUT') {
695 else if (m === 'GET') {
696 uri = _concat(uri, f);
701 if (c.data && m === 'GET') {
702 uri = _concat(uri, c.data);
705 if (c.data && m === 'POST') {
706 c.headers = Y.merge({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, c.headers);
710 return Y.io.xdr(uri, o, c);
714 o.c.onreadystatechange = function() { _readyState(o, c); };
718 o.c.open(m, uri, s ? false : true);
719 // Will work only in browsers that implement the
720 // Cross-Origin Resource Sharing draft.
721 if (c.xdr && c.xdr.credentials) {
722 o.c.withCredentials = true;
727 // This exception is usually thrown by browsers
728 // that do not support native XDR transactions.
729 return _resend(o, u, c, oD);
733 _setHeaders(o.c, c.headers);
736 // Using "null" with HTTP POST will result in a request
737 // with no Content-Length header defined.
738 o.c.send(c.data || '');
741 a = ['status', 'statusText', 'responseText', 'responseXML'];
742 r = c.arguments ? { id: o.id, arguments: c.arguments } : { id: o.id };
744 for (j = 0; j < 4; j++) {
748 r.getAllResponseHeaders = function() { return d.getAllResponseHeaders(); };
749 r.getResponseHeader = function(h) { return d.getResponseHeader(h); };
751 _handleResponse(o, c);
758 // This exception is usually thrown by browsers
759 // that do not support native XDR transactions.
760 return _resend(o, u, c, oD);
764 // If config.timeout is defined, and the request is standard XHR,
765 // initialize timeout polling.
767 _startTimeout(o, c.timeout);
773 return o.c ? _ioCancel(o, 'abort') : false;
775 isInProgress: function() {
776 return o.c ? o.c.readyState !== 4 && o.c.readyState !== 0 : false;
781 _io.start = _ioStart;
782 _io.complete = _ioComplete;
783 _io.success = _ioSuccess;
784 _io.failure = _ioFailure;
787 _io._timeout = _timeout;
789 //--------------------------------------
790 // Begin public interface definition
791 //--------------------------------------
793 * @description Method that stores default client headers for all transactions.
794 * If a label is passed with no value argument, the header will be deleted.
795 * This is the interface for _setHeader().
800 * @param {string} l - HTTP header
801 * @param {string} v - HTTP header value
804 _io.header = _setHeader;
807 * @description Method for requesting a transaction. This
808 * is the interface for _io().
813 * @param {string} uri - qualified path to transaction resource.
814 * @param {object} c - configuration object for the transaction.
822 }, '3.3.0' ,{requires:['event-custom-base', 'querystring-stringify-simple']});