views:

95

answers:

3

I plan on using JSONP to call an external webservice to get around the fact that I dont want to create a global function that could potentially conflict with the calling page. I thought that creating a random function name and passing it up would work. Something like this:

<script src="www.foo.com/b?cb=d357534">

where cb is the callback function name, the server would return

d357534({my json data});

what i want to know is how to create the random function name, im sure i could use eval but is this the best way to go about it?

essentially, what i am trying to do is this:

var d + Math.floor(Math.random()*1000001) = function(){...   
+6  A: 

This should do what you want. You need to save the function name somewhere so that you can pass it to the server, but you can do that inside of a local scope to avoid polluting your global namespace.

var functionName = 'd' + Math.floor(Math.random()*1000001);
window[functionName] = function() { ... }
Brian Campbell
this works perfectly, thanks!
Russ Bradberry
you can also put a check in, to verify that it does not exist, prior to creating it.
Cheeso
A: 

To make a randomly-named global variable you could do this:

window['randomvar' + Math.floor(Math.random()*1000001)] = function() { ... };

now of course you've got the problem of remembering the random name somewhere. You could make up a random name for that variable too. Then you'd have to remember the name of that variable, so that you could look at its value and then know how to find your function. After a while, things are going to start getting weird.

Pointy
A: 

Why don't just use a counter and increment it each time you need a new function:

var name = "callback" + window.COUNTER++;
window[name] = function() { ... };

If you want to avoid littering the global namespace with too many references you could (and should) attach the counter and callbacks to a single global object:

var JSONP = window.JSONP;
var name = "callback" + JSONP.COUNTER++;
JSONP[name] = function() { ... };

In this case you could call the method like this:

JSONP.callback_12(json);

Of coarse you have to initialize the JSONPobject and the COUNTER variable first.

Fabian Jakobs