UNPKG

2.51 kBJavaScriptView Raw
1var isFunction = require('x-common-utils/isFunction');
2var JSONPResponse = require('../class/JSONPResponse');
3var fireCallbacks = require('../shared/fireCallbacks');
4var noop = require('../shared/noop');
5var constants = require('../shared/constants');
6var ERR_CANCELED = constants.ERR_CANCELED;
7var ERR_NETWORK = constants.ERR_NETWORK;
8var ERR_RESPONSE = constants.ERR_RESPONSE;
9var ERR_TIMEOUT = constants.ERR_TIMEOUT;
10
11/**
12 * Add event listeners to JSONP request.
13 *
14 * @param {JSONPRequest} request The JSONP request.
15 * @param {string} callbackName The callback name used to define the global JSONP callback.
16 */
17function 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 * The function finish the request.
32 *
33 * @param {string} code The error code on error. If no error occured, the code is `null`.
34 */
35 var finish = function (code) {
36 // Set finish to the no operation function.
37 finish = noop;
38
39 // Mark this request as finished.
40 request.finished = true;
41
42 // Clear listeners.
43 window[callbackName] = noop;
44 script.onerror = null;
45
46 // Clear timeout.
47 if (timeoutId !== null) {
48 clearTimeout(timeoutId);
49 timeoutId = null;
50 }
51
52 // Fire callbacks.
53 fireCallbacks(code, response);
54 };
55
56 // Define the callback function.
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 // Catch the error.
71 script.onerror = function () {
72 finish(ERR_NETWORK);
73 };
74
75 /**
76 * Cancel the request.
77 */
78 request.cancel = function () {
79 finish(ERR_CANCELED);
80 };
81
82 // Add timeout listener
83 if (timeout > 0) {
84 timeoutId = setTimeout(function () {
85 finish(ERR_TIMEOUT);
86 }, timeout);
87 }
88}
89
90module.exports = addEventListeners;