Skip to content

Instantly share code, notes, and snippets.

@gustavopaes
Created May 25, 2016 16:21
Show Gist options
  • Save gustavopaes/1f7187ccf1a39ffa202d6e60cf89e04c to your computer and use it in GitHub Desktop.
Save gustavopaes/1f7187ccf1a39ffa202d6e60cf89e04c to your computer and use it in GitHub Desktop.
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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment