source: trunk/instant_messenger/js/connector.js @ 305

Revision 305, 6.7 KB checked in by niltonneto, 16 years ago (diff)

Correçoes

  • Property svn:executable set to *
Line 
1(function()
2{
3        var _THREADS = [];
4        var _ie;
5
6        // xhr = XMLHttpRequest
7        function _xhr()
8        {
9                try
10                {
11                        return new XMLHttpRequest();
12                }
13                catch (_e)
14                {
15                        _ie = true;
16                        try
17                        {
18                                return new ActiveXObject('Msxml2.XMLHTTP');
19                        }
20                        catch (_e1)
21                        {
22                                try
23                                {
24                                        return new ActiveXObject('Microsoft.XMLHTTP');
25                                }
26                                catch (_e2)
27                                {
28                                        return false;
29                                }
30                        }
31                }
32        }
33
34        function _HANDLER()
35        {
36                var _ID = arguments[0];
37
38                if ( _ie && _THREADS[_ID]._XHR.readyState != 4 )
39                        return false;
40
41                switch ( _THREADS[_ID]._XHR.readyState )
42                {
43                        case 3 :
44                                if ( _THREADS[_ID]._HANDLER.stream )
45                                {
46                                        var _data = _THREADS[_ID]._XHR.responseText.substr(_THREADS[_ID]._index).replace(/^ +| +$/g, '');
47                                        //alert(_data);
48                                        _THREADS[_ID]._rtlen = _THREADS[_ID]._XHR.responseText.length;
49
50                                        if ( _THREADS[_ID]._index < _THREADS[_ID]._rtlen && _data.length )
51                                                try
52                                                {
53                                                        _THREADS[_ID]._HANDLER.stream(_data);
54                                                }
55                                                catch(_e)
56                                                {
57                                                        alert("#stream\n\n" + _e + "\n\n" + _e.description);
58                                                }
59
60                                        _THREADS[_ID]._index = _THREADS[_ID]._rtlen;
61                                }
62                        break;
63                        case 4 :
64                                switch ( _THREADS[_ID]._XHR.status )
65                                {
66                                        case 200:
67                                                var _data = ( _THREADS[_ID]._MODE == 'XML' ) ?
68                                                        _THREADS[_ID]._XHR.responseXML :
69                                                        _THREADS[_ID]._XHR.responseText;
70
71                                                if ( _ie && _THREADS[_ID]._HANDLER.stream )
72                                                        _THREADS[_ID]._HANDLER.stream(_data);
73
74                                                var _request = ( _THREADS[_ID]._HANDLER.request ) ?
75                                                        _THREADS[_ID]._HANDLER.request : false;
76
77                                                delete _THREADS[_ID];
78
79                                                if ( _request )
80                                                        try
81                                                        {
82                                                                _request(_data);
83                                                        }
84                                                        catch(_e)
85                                                        {
86                                                                alert("#request\n\n" + _e + "\n\n" + _e.description);
87                                                        }
88
89                                        break; // [case : status 200]
90                                        case 404:
91                                                delete _THREADS[_ID];
92                                                alert('Page Not Found!');
93                                        break; // [case : status 404]
94                                        default:
95                                                delete _THREADS[_ID];
96                                }
97                        break;
98                        default :
99                }
100        }
101
102        function _execute()
103        {
104                var _ID = arguments[0];
105                var _ACTION = 'act=' + _ID;
106                var _TARGET = this._PATH;
107                var _SEND = null;
108
109                if ( _TARGET != '' && _TARGET.lastIndexOf('/') != (_TARGET.length - 1) )
110                        _TARGET += '/';
111
112                _TARGET += ( this._CONTROLLER ) ?
113                        this._CONTROLLER  : 'controller.php';
114
115                if ( _THREADS[_ID]._METHOD == 'GET' )
116                        _TARGET += '?' + _ACTION;
117
118                _THREADS[_ID]._XHR.open(_THREADS[_ID]._METHOD, _TARGET, true);
119
120                if ( _THREADS[_ID]._METHOD == 'POST' )
121                {
122                        _THREADS[_ID]._XHR.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
123                        _THREADS[_ID]._XHR.setRequestHeader('Cache-Control',  'no-store, no-cache, must-revalidate');
124                        _THREADS[_ID]._XHR.setRequestHeader('Cache-Control', 'post-check=0, pre-check=0');
125                        _THREADS[_ID]._XHR.setRequestHeader('Pragma', 'no-cache');
126                        _SEND = _ACTION + '&' + arguments[1];
127                }
128
129                _THREADS[_ID]._XHR.onreadystatechange = function(){_HANDLER(_ID);};
130                _THREADS[_ID]._XHR.send(_SEND);
131        }
132
133        function usage()
134        {
135                return ""+
136                        "Description:\n"+
137                        "\t<obj>.go(string access, [mixed handler[, mixed post]])\n\n"+
138                        "Parameters:\n"+
139                        "\taccess : assinatura de acesso à camada de controle.\n"+
140                        "\thandler : uma função a ser executada no fim da requisição\n"+
141                        "\t\tou um objeto que poderá conter dois índices sendo\n"+
142                        "\t\tque ambos deverão ser uma função que será executada\n"+
143                        "\t\tconforme o status do objeto xhr, sendo que na posição\n"+
144                        "\t\t'stream' será a função a ser executada a cada iteração\n"+
145                        "\t\tdo objeto xhr e na posição 'request' será a função\n"+
146                        "\t\ta ser executada no fim da requisição.\n"+
147                        "\tpost : se especificado deverá ser uma query string ou um\n"+
148                        "\tXML bem formatado.\n\n";
149        }
150
151        // @PARAM arguments[0] string :
152        //              assinatura de acesso à camada de controle
153        //
154        // @PARAM arguments[1] object :
155        //              OBS : neste caso a conexão assumirá que se trata de uma stream
156        //              objeto contendo dois duas funções, sendo,
157        //              no índice stream deverá conter uma função que será execultada
158        //              a cada mudança de status do objeto xhr
159        //      or
160        // @PARAM arguments[1] function : funcão a ser executada no retorno da
161        //              requisição
162        //              OBS : neste caso a conexão assumirá que se trata de uma
163        //              requisição função que será execultada no final da requisição
164        //
165        // @PARAM arguments[2] string :
166        //              este parâmetro define se a conexão é via GET ou POST
167        //              caso o parâmetro não esteja presente a conexão será execultada
168        //              via GET, por outro lado, caso ele exista deverá ser uma query
169        //              string válida ou um xml bem formatado
170        //
171        function go()
172        {
173                var _argv = arguments;
174                var _argc = _argv.length;
175                var _ID = _argv[0];
176                var _POST;
177                if ( _argc < 1 || _argc > 3 )
178                        return {'error' : "#0\n\n" + usage()};
179
180                if ( typeof _ID != 'string' )
181                        return {'error' : "#1\n\n" + usage()};
182
183                if ( _THREADS[_ID] )
184                        return {'error' : '#2 - there is a equal request running'};
185
186                _THREADS[_ID] = {
187                        '_HANDLER'      : {},
188                        '_METHOD'       : ( _argv[2] ) ? 'POST' : 'GET',  // [GET | POST]
189                        '_MODE'         : null, // [XML | TEXT]
190                        '_TYPE'         : null, // [4 for request | 3 for stream]
191                        '_XHR'          : null  // [4 for request | 3 for stream]
192                };
193
194                if ( _argv[2] )
195                        _POST = _argv[2];
196
197                if ( _argv[1] )
198                        switch ( typeof _argv[1] )
199                        {
200                                case 'function' :
201                                        _THREADS[_ID]._HANDLER = {'request' : _argv[1]};
202                                break;
203                                case 'object' :
204                                        for ( var i in _argv[1] )
205                                                if ( i != 'stream' && i != 'request' )
206                                                {
207                                                        delete _THREADS[_ID];
208                                                        return {'error' : "#3\n\n" + usage()};
209                                                }
210                                                else if ( i == 'stream' )
211                                                {
212                                                        _THREADS[_ID]._index = 0;
213                                                        _THREADS[_ID]._rtlen = 0;
214                                                }
215                                                _THREADS[_ID]._HANDLER = _argv[1];
216                                break;
217                                case 'string' :
218                                        if ( _argc == 2 )
219                                        {
220                                                _THREADS[_ID]._METHOD = 'POST';
221                                                _POST = _argv[1];
222                                        }
223                                break;
224                                default :
225                                        //delete _THREADS[_ID];
226                                        //return {'error' : "#4\n\n" + usage()};
227                        }
228
229                if ( !(_THREADS[_ID]._XHR = _xhr()) )
230                        return {'error' : "#4 it cannot make a xhr object"};
231
232                ( _THREADS[_ID]._METHOD == 'GET' ) ?
233                        _execute.call(this, _ID) : _execute.call(this, _ID, _POST);
234                return {'success' : "your thread is running and the response "+
235                                                        "will be manipulated by the handler"};
236        }
237
238        function Connector()
239        {
240                var _argv = arguments;
241                this._PATH = ( _argv.length > 0 ) ?
242                        _argv[0] : '';
243                this._CONTROLLER = ( _argv.length == 2 ) ?
244                        _argv[1] : false;
245        }
246
247        Connector.prototype.go = go;
248        window.IMConnector = Connector;
249
250        var _unload_event = window.onbeforeunload;
251        window.onbeforeunload = function()
252        {
253                for ( var _ID in _THREADS )
254                {
255                        //if ( _THREADS[_ID]._XHR.abort )
256                        try
257                        {
258                                if ( _THREADS[_ID]._XHR && _THREADS[_ID]._XHR.abort )
259                                        _THREADS[_ID]._XHR.abort();
260                                delete _THREADS[_ID];
261                        }
262                        catch(e)
263                        {
264                        }
265                }
266
267                if ( typeof _unload_event == 'function' )
268                        return _unload_event();
269        };
270}
271)();
Note: See TracBrowser for help on using the repository browser.