2
Copyright (c) 2008, Yahoo! Inc. All rights reserved.
3
Code licensed under the BSD License:
4
http://developer.yahoo.net/yui/license.txt
7
YUI.add('io-base', function(Y) {
10
* HTTP communications module.
15
* The io class is a utility that brokers HTTP requests through a simplified
16
* interface. Specifically, it allows JavaScript to make HTTP requests to
17
* a resource without a page reload. The underlying transport for making
18
* same-domain requests is the XMLHttpRequest object. YUI.io can also use
19
* Flash, if specified as a transport, for cross-domain requests.
26
* @description This event is fired by YUI.io when a transaction is initiated..
29
var E_START = 'io:start',
33
* @description This event is fired by YUI.io when a transaction is complete and
34
* all response data are available.
37
E_COMPLETE = 'io:complete',
41
* @description This event is fired by YUI.io when a transaction is complete and
42
* the HTTP status resolves to HTTP2xx.
45
E_SUCCESS = 'io:success',
49
* @description This event is fired by YUI.io when a transaction is complete and
50
* the HTTP status resolves to HTTP4xx, 5xx and above.
53
E_FAILURE = 'io:failure',
57
* @description This event is fired by YUI.io when a transaction is aborted
58
* explicitly or by a defined config.timeout.
63
//--------------------------------------
65
//--------------------------------------
67
* @description A transaction counter that increments for each transaction.
69
* @property transactionId
77
* @description Object of default HTTP headers to be initialized and sent
78
* for all transactions.
86
'X-Requested-With' : 'XMLHttpRequest'
90
* @description Object that stores timeout values for any transaction with
91
* a defined "timeout" configuration property.
100
//--------------------------------------
102
//--------------------------------------
108
* @description Method for requesting a transaction. _io() is implemented as
109
* yui.io(). Each transaction may include a configuration object. Its
112
* method: HTTP method verb (e.g., GET or POST). If this property is not
113
* not defined, the default value will be GET.
115
* data: This is the name-value string that will be sent as the transaction
116
* data. If the request is HTTP GET, the data become part of
117
* querystring. If HTTP POST, the data are sent in the message body.
119
* xdr: Defines the transport to be used for cross-domain requests. By
120
* setting this property, the transaction will use the specified
121
* transport instead of XMLHttpRequest. Currently, the only alternate
122
* transport supported is Flash (e.g., { xdr: 'flash' }).
124
* form: This is a defined object used to process HTML form as data. The
127
* id: object, //HTML form object or id of HTML form
128
* useDisabled: boolean, //Allow disabled HTML form field values
129
* to be sent as part of the data.
132
* on: This is a defined object used to create and handle specific
133
* events during a transaction lifecycle. These events will fire in
134
* addition to the global io events. The events are:
135
* start - This event is fired when a request is sent to a resource.
136
* complete - This event fires when the transaction is complete.
137
* success - This event fires when the response status resolves to
139
* failure - This event fires when the response status resolves to
140
* HTTP 4xx, 5xx, and beyond.
141
* abort - This even is fired when a transaction abort is fire by
142
* timeout, or when it is manually aborted.
144
* The properties are:
146
* start: function(id, args){},
147
* complete: function(id, responseobject, args){},
148
* success: function(id, responseobject, args){},
149
* failure: function(id, responseobject, args){},
150
* abort: function(id, args){}
152
* Each property can reference a function or be written as an
155
* context: Object reference for an event handler when it is implemented
156
* as a method of a base object. Defining "context" will preserve
157
* the proper reference of "this" used in the event handler.
158
* headers: This is a defined object of client headers, as many as.
159
* desired for the transaction. These headers are sentThe object
165
* timeout: This value, defined as milliseconds, is a time threshold for the
166
* transaction. When this threshold is reached, and the transaction's
167
* Complete event has not yet fired, the transaction will be aborted.
168
* arguments: Object, array, string, or number passed to all registered
169
* event handlers. This value is available as the second
170
* argument in the "start" and "abort" event handlers; and, it is
171
* the third argument in the "complete", "success", and "failure"
177
* @param {string} uri - qualified path to transaction resource.
178
* @param {object} c - configuration object for the transaction.
181
function _io(uri, c) {
183
o = _create((arguments.length === 3) ? arguments[2] : null, c),
184
m = (c.method) ? c.method.toUpperCase() : 'GET',
185
d = (c.data) ? c.data : null,
188
/* Determine configuration properties */
189
// If config.form is defined, perform data operations.
193
u = Y.io._upload(o, uri, c);
197
// Serialize the HTML form into a string of name-value pairs.
198
f = Y.io._serialize(c.form);
199
// If config.data is defined, concatenate the data to the form string.
206
_setHeader('Content-Type', 'application/x-www-form-urlencoded');
208
else if (m === 'GET') {
209
uri = _concat(uri, f);
212
else if (d && m === 'GET') {
213
uri = _concat(uri, c.data);
215
else if (d && m === 'POST') {
216
_setHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
220
Y.io._xdr(uri, o, c);
224
// If config.timeout is defined, and the request is standard XHR,
225
// initialize timeout polling.
229
/* End Configuration Properties */
231
o.c.onreadystatechange = function() { _readyState(o, c); };
237
_setHeaders(o.c, (c.headers || {}));
239
o.abort = function () {
243
o.isInProgress = function() {
244
return o.c.readyState !== 4 && o.c.readyState !== 0;
246
// Do not pass null, in the absence of data, as this
247
// will result in a POST request with no Content-Length
249
_async(o, (d || ''), c);
255
* @description Method for creating and subscribing transaction events.
260
* @param {string} e - event to be published
261
* @param {object} c - configuration object for the transaction.
265
function _tPubSub(e, c){
266
var event = new Y.Event.Target().publish('transaction:' + e);
267
event.subscribe(c.on[e], (c.context || this), c.arguments);
273
* @description Fires event "io:start" and creates, fires a
274
* transaction-specific start event, if config.on.start is
280
* @param {number} id - transaction id
281
* @param {object} c - configuration object for the transaction.
285
function _ioStart(id, c) {
286
// Set default value of argument c, property "on" to Object if
287
// the property is null or undefined.
289
var m = Y.io._fn || {},
290
fn = (m && m[id]) ? m[id] : null,
294
c.on.start = fn.start;
300
event = _tPubSub('start', c);
306
* @description Fires event "io:complete" and creates, fires a
307
* transaction-specific "complete" event, if config.on.complete is
310
* @method _ioComplete
313
* @param {object} o - transaction object.
314
* @param {object} c - configuration object for the transaction.
318
function _ioComplete(o, c) {
319
// Set default value of argument c, property "on" to Object if
320
// the property is null or undefined.
324
Y.fire(E_COMPLETE, o.id, o.c);
326
event = _tPubSub('complete', c);
327
event.fire(o.id, o.c);
332
* @description Fires event "io:success" and creates, fires a
333
* transaction-specific "success" event, if config.on.success is
339
* @param {object} o - transaction object.
340
* @param {object} c - configuration object for the transaction.
344
function _ioSuccess(o, c) {
345
// Set default value of argument c, property "on" to Object if
346
// the property is null or undefined.
348
var m = Y.io._fn || {},
349
fn = (m && m[o.id]) ? m[o.id] : null,
353
c.on.success = fn.success;
355
//Decode the response from IO.swf
356
o.c.responseText = decodeURI(o.c.responseText);
359
Y.fire(E_SUCCESS, o.id, o.c);
361
event = _tPubSub('success', c);
362
event.fire(o.id, o.c);
365
_destroy(o, (c.xdr) ? true : false );
369
* @description Fires event "io:failure" and creates, fires a
370
* transaction-specific "failure" event, if config.on.failure is
376
* @param {object} o - transaction object.
377
* @param {object} c - configuration object for the transaction.
381
function _ioFailure(o, c) {
382
// Set default value of argument c, property "on" to Object if
383
// the property is null or undefined.
385
var m = Y.io._fn || {},
386
fn = (m && m[o.id]) ? m[o.id] : null,
390
c.on.failure = fn.failure;
392
//Decode the response from IO.swf
393
o.c.responseText = decodeURI(o.c.responseText);
396
Y.fire(E_FAILURE, o.id, o.c);
398
event = _tPubSub('failure', c);
399
event.fire(o.id, o.c);
402
_destroy(o, (c.xdr) ? true : false );
406
* @description Fires event "io:abort" and creates, fires a
407
* transaction-specific "abort" event, if config.on.abort is
413
* @param {object} o - Transaction object generated by _create().
414
* @param {object} c - Configuration object passed to YUI.io().
418
function _ioAbort(o, c) {
419
// Set default value of argument c, property "on" to Object if
420
// the property is null or undefined.
422
var m = Y.io._fn || {},
423
fn = (m && m[o.id]) ? m[o.id] : null,
426
if(o && o.c && !c.xdr) {
427
// Terminate the transaction
430
// Clear the timeout poll for this specific transaction.
438
c.on.abort = fn.abort;
442
Y.fire(E_ABORT, o.id);
444
event = _tPubSub('abort', c);
448
_destroy(o, (c.xdr) ? true : false );
452
* @description Method that increments _transactionId for each transaction.
460
var id = transactionId;
467
* @description Method that creates a unique transaction object for each
473
* @param {number} s - URI or root data.
474
* @param {number} c - configuration object
477
function _create(i, c) {
479
o.id = Y.Lang.isNumber(i) ? i : _id();
482
o.c = Y.io._transportMap[c.xdr.use];
484
else if (c.form && c.form.upload) {
495
* @description Method that creates the XMLHttpRequest transport
503
return (w.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
507
* @description Method that concatenates string data for HTTP GET transactions.
512
* @param {string} s - URI or root data.
513
* @param {string} d - data to be concatenated onto URI.
516
function _concat(s, d) {
517
s += ((s.indexOf('?') == -1) ? '?' : '&') + d;
522
* @description Method that stores default client headers for all transactions.
523
* If a label is passed with no value argument, the header will be deleted.
528
* @param {string} l - HTTP header
529
* @param {string} v - HTTP header value
532
function _setHeader(l, v) {
542
* @description Method that sets all HTTP headers to be sent in a transaction.
544
* @method _setHeaders
547
* @param {object} o - XHR instance for the specific transaction.
548
* @param {object} h - HTTP headers for the specific transaction, as defined
549
* in the configuration object passed to YUI.io().
552
function _setHeaders(o, h) {
556
for (p in _headers) {
557
if (_headers.hasOwnProperty(p)) {
559
// Configuration headers will supersede IO preset headers,
570
if (h.hasOwnProperty(p)) {
571
o.setRequestHeader(p, h[p]);
576
function _open(o, m, uri) {
577
o.open(m, uri, true);
581
* @description Method that sends the transaction request.
586
* @param {object} o - Transaction object generated by _create().
587
* @param {string} d - Transaction data.
588
* @param {object} c - Configuration object passed to YUI.io().
591
function _async(o, d, c) {
597
* @description Starts timeout count if the configuration object
598
* has a defined timeout property.
600
* @method _startTimeout
603
* @param {object} o - Transaction object generated by _create().
604
* @param {object} c - Configuration object passed to YUI.io().
607
function _startTimeout(o, c) {
608
_timeout[o.id] = w.setTimeout(function() { _ioAbort(o, c); }, c.timeout);
612
* @description Clears the timeout interval started by _startTimeout().
614
* @method _clearTimeout
617
* @param {number} id - Transaction id.
620
function _clearTimeout(id) {
621
w.clearTimeout(_timeout[id]);
626
* @description Event handler bound to onreadystatechange.
628
* @method _readyState
631
* @param {object} o - Transaction object generated by _create().
632
* @param {object} c - Configuration object passed to YUI.io().
635
function _readyState(o, c) {
636
if (o.c.readyState === 4) {
641
_handleResponse(o, c);
646
* @description Method that determines if a transaction response qualifies
647
* as success or failure, based on the response HTTP status code, and
648
* fires the appropriate success or failure events.
650
* @method _handleResponse
653
* @param {object} o - Transaction object generated by _create().
654
* @param {object} c - Configuration object passed to YUI.io().
657
function _handleResponse(o, c) {
660
if (o.c.status && o.c.status !== 0) {
672
* IE reports HTTP 204 as HTTP 1223.
673
* However, the response data are still available.
675
* setTimeout() is used to prevent transactions from becoming
676
* synchronous, in IE, when the response data are read from cache
679
if (status >= 200 && status < 300 || status === 1223) {
680
w.setTimeout( function() { _ioSuccess(o, c); }, 0);
683
w.setTimeout( function() {_ioFailure(o, c); }, 0);
687
function _destroy(o, isTransport) {
688
// IE6 will throw a "Type Mismatch" error if the event handler is set to "null".
689
if(w.XMLHttpRequest && !isTransport) {
691
o.c.onreadystatechange = null;
699
_io.start = _ioStart;
700
_io.complete = _ioComplete;
701
_io.success = _ioSuccess;
702
_io.failure = _ioFailure;
703
_io.abort = _ioAbort;
705
_io._timeout = _timeout;
707
//--------------------------------------
708
// Begin public interface definition
709
//--------------------------------------
711
* @description Method that stores default client headers for all transactions.
712
* If a label is passed with no value argument, the header will be deleted.
713
* This is the interface for _setHeader().
718
* @param {string} l - HTTP header
719
* @param {string} v - HTTP header value
722
_io.header = _setHeader;
725
* @description Method for requesting a transaction. This
726
* is the interface for _io().
731
* @param {string} uri - qualified path to transaction resource.
732
* @param {object} c - configuration object for the transaction.