Last active
May 28, 2016 23:11
-
-
Save tweinfeld/da5b94f5102a1caed0a5 to your computer and use it in GitHub Desktop.
A JSONP mixin for Lodash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_.jsonp('https://api.ipify.org/?format=jsonp', function(err, value){ | |
console.log(err || value); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_.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