Skip to content

Instantly share code, notes, and snippets.

@tweinfeld
Last active May 28, 2016 23:11
Show Gist options
  • Save tweinfeld/da5b94f5102a1caed0a5 to your computer and use it in GitHub Desktop.
Save tweinfeld/da5b94f5102a1caed0a5 to your computer and use it in GitHub Desktop.
A JSONP mixin for Lodash
_.jsonp('https://api.ipify.org/?format=jsonp', function(err, value){
console.log(err || value);
});
_.mixin({
"jsonp": function(url, cb, receiverParameterName){
var receiverName = _(_.range(10)).map(_.partial(_.sample,"abcdefghijklmnopqrstuvexyzABCDEFGHIJKLMNOPRQAT",1)).join(''),
urlSplit = url.split('?'),
cbWrapper = _.once(_.flow(cb || _.noop, function(){ window[receiverName] = undefined; }));
window[receiverName] = _.partial(cbWrapper, null);
setTimeout(_.partial(cbWrapper, new Error('Connection timed out')), 3000);
var script = document.createElement('script');
script.src = [urlSplit.shift()]
.concat(
urlSplit
.map(function(str){ return str.split('&') })
.concat([receiverParameterName || "callback", receiverName].join('='))
.join('&')
).join('?');
document.querySelector('body').appendChild(script);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment