diff --git a/modules/services/streetside.js b/modules/services/streetside.js index d4dbb2c0d..4b140a57b 100644 --- a/modules/services/streetside.js +++ b/modules/services/streetside.js @@ -247,7 +247,7 @@ function getBubbles(url, tile, callback) { jsCallback: '{callback}' }); - jsonpRequest(urlForRequest, function (data) { + return jsonpRequest(urlForRequest, function (data) { if (!data || data.error) { callback(null); } else { diff --git a/modules/util/jsonp_request.js b/modules/util/jsonp_request.js index b81896a22..ba5d32c27 100644 --- a/modules/util/jsonp_request.js +++ b/modules/util/jsonp_request.js @@ -1,43 +1,61 @@ import { select as d3_select } from 'd3-selection'; - var jsonpCache = {}; window.jsonpCache = jsonpCache; export function jsonpRequest(url, callback) { - - if (window.JSONP_FIX) { - if (window.JSONP_DELAY === 0) { - callback(window.JSONP_FIX); - } else { - setTimeout(function() { - callback(window.JSONP_FIX); - }, window.JSONP_DELAY || 0); - } - return; - } - - function rand() { - var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', - c = '', i = -1; - while (++i < 15) c += chars.charAt(Math.floor(Math.random() * 52)); - return c; - } - - function create(url) { - var e = url.match(/callback=(\w+)/), - c = e ? e[1] : rand(); - jsonpCache[c] = function(data) { - callback(data); - delete jsonpCache[c]; - script.remove(); + var request = { + abort: function() {} }; - return 'jsonpCache.' + c; - } - var cb = create(url), - script = d3_select('head') - .append('script') - .attr('type', 'text/javascript') - .attr('src', url.replace(/(\{|%7B)callback(\}|%7D)/, cb)); + if (window.JSONP_FIX) { + if (window.JSONP_DELAY === 0) { + callback(window.JSONP_FIX); + } else { + var t = window.setTimeout(function() { + callback(window.JSONP_FIX); + }, window.JSONP_DELAY || 0); + + request.abort = function() { window.clearTimeout(t); }; + } + + return request; + } + + function rand() { + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; + var c = ''; + var i = -1; + while (++i < 15) c += chars.charAt(Math.floor(Math.random() * 52)); + return c; + } + + function create(url) { + var e = url.match(/callback=(\w+)/); + var c = e ? e[1] : rand(); + + jsonpCache[c] = function(data) { + if (jsonpCache[c]) { + callback(data); + } + finalize(); + }; + + function finalize() { + delete jsonpCache[c]; + script.remove(); + } + + request.abort = finalize; + return 'jsonpCache.' + c; + } + + var cb = create(url); + + var script = d3_select('head') + .append('script') + .attr('type', 'text/javascript') + .attr('src', url.replace(/(\{|%7B)callback(\}|%7D)/, cb)); + + return request; }