gustavopaes
5/25/2016 - 4:21 PM

mithril.js feature request: static jsonp callback name

mithril.js feature request: static jsonp callback name

  window.jsonpRequestQueue = {};
  function handleJsonp(options) {
    var callbackKey = options.callback || ("mithril_callback_" +
      new Date().getTime() + "_" +
      (Math.round(Math.random() * 1e16)).toString(36))

    var script = $document.createElement("script")

    // callback já existe, faz fila
    if(typeof global[callbackKey] === 'function') {
      jsonpRequestQueue[callbackKey] = (jsonpRequestQueue[callbackKey] || []);
      jsonpRequestQueue[callbackKey].push(options);

      return true;
    }

    global[callbackKey] = function (resp) {
      script.parentNode.removeChild(script)
      options.onload({
        type: "load",
        target: {
          responseText: resp
        }
      })
      global[callbackKey] = undefined

      if(jsonpRequestQueue[callbackKey] && jsonpRequestQueue[callbackKey].length) {
        handleJsonp(jsonpRequestQueue[callbackKey].shift());
      }
    }

    script.onerror = function () {
      script.parentNode.removeChild(script)

      options.onerror({
        type: "error",
        target: {
          status: 500,
          responseText: JSON.stringify({
            error: "Error making jsonp request"
          })
        }
      })
      global[callbackKey] = undefined

      return false
    }

    script.onload = function () {
      return false
    }

    script.src = options.url +
      (options.url.indexOf("?") > 0 ? "&" : "?") +
      (options.callbackKey ? options.callbackKey : "callback") +
      "=" + callbackKey +
      (options.data ? "&" + buildQueryString(options.data || {}) : '')

    $document.body.appendChild(script)
  }