Reputation: 10974
I have an external javascript file which is loaded dynamically, and it has an oncomplete=
variable, which increases its value each time that it is called. For example:
Because of that I need to dynamically create functions to execute the oncomplete= callback each time. That means, that I need to create functions with these names:
This is my current code, which creates a specific name function:
var sayHello = function (){
console.log('hello');
};
sayHello();
The question is: How can I create temporal functions with dynamically generated names in jQuery?
Upvotes: 0
Views: 213
Reputation: 838
This is more of a pure javascript question. Assuming the global scope (window) for simplicity,
var sayHello = function () { /* body */ };
is equivalent to
window['sayHello'] = function () { /* body */ };
Now, obviously, you don't want to pollute the global scope like that, so you can do the same thing with any other object.
dynamicFunctions = {};
var oncomplete = 'sayHello1';
dynamicFunctions[oncomplete] = function () { console.log('hello'); };
dynamicFunctions[oncomplete]();
// outputs hello to the console
One thing to keep in mind, though, is why you're doing it this way in the first place. As I'm not sure of your specific requirements, is there a reason that you can't do something like this?
// load external.js?oncomplete=sayHello&increment=4
sayHello(increment);
Upvotes: 2