1 | var isFunction = require('x-common-utils/isFunction');
|
2 | var JSONPResponse = require('../class/JSONPResponse');
|
3 | var fireCallbacks = require('../shared/fireCallbacks');
|
4 | var noop = require('../shared/noop');
|
5 | var constants = require('../shared/constants');
|
6 | var ERR_CANCELED = constants.ERR_CANCELED;
|
7 | var ERR_NETWORK = constants.ERR_NETWORK;
|
8 | var ERR_RESPONSE = constants.ERR_RESPONSE;
|
9 | var ERR_TIMEOUT = constants.ERR_TIMEOUT;
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | function addEventListeners(request, callbackName) {
|
18 | var script = request.script;
|
19 | var options = request.options;
|
20 | var requestType = request.requestType;
|
21 | var isResponseOk = options.isResponseOk;
|
22 | var response = new JSONPResponse(request);
|
23 | var timeout = parseInt(options.timeout, 10) || 0;
|
24 | var timeoutId = null;
|
25 |
|
26 | if (timeout <= 0) {
|
27 | timeout = parseInt(options.jsonpDefaultTimeout, 10) || 0;
|
28 | }
|
29 |
|
30 | |
31 |
|
32 |
|
33 |
|
34 |
|
35 | var finish = function (code) {
|
36 |
|
37 | finish = noop;
|
38 |
|
39 |
|
40 | request.finished = true;
|
41 |
|
42 |
|
43 | window[callbackName] = noop;
|
44 | script.onerror = null;
|
45 |
|
46 |
|
47 | if (timeoutId !== null) {
|
48 | clearTimeout(timeoutId);
|
49 | timeoutId = null;
|
50 | }
|
51 |
|
52 |
|
53 | fireCallbacks(code, response);
|
54 | };
|
55 |
|
56 |
|
57 | window[callbackName] = function (responseJSON) {
|
58 | request.responseJSON = responseJSON;
|
59 | if (isFunction(isResponseOk)) {
|
60 | if (isResponseOk(requestType, response)) {
|
61 | finish(null);
|
62 | } else {
|
63 | finish(ERR_RESPONSE);
|
64 | }
|
65 | } else {
|
66 | finish(null);
|
67 | }
|
68 | };
|
69 |
|
70 |
|
71 | script.onerror = function () {
|
72 | finish(ERR_NETWORK);
|
73 | };
|
74 |
|
75 | |
76 |
|
77 |
|
78 | request.cancel = function () {
|
79 | finish(ERR_CANCELED);
|
80 | };
|
81 |
|
82 |
|
83 | if (timeout > 0) {
|
84 | timeoutId = setTimeout(function () {
|
85 | finish(ERR_TIMEOUT);
|
86 | }, timeout);
|
87 | }
|
88 | }
|
89 |
|
90 | module.exports = addEventListeners;
|