Sergio Romero
Sergio Romero

Reputation: 6597

In javascript how do I call a function dynamically added to an object

Keeping up with the Javascript learning effort. I am looking at the following code which aims to add functions to an object keeping them unique, something like adding callback functions to an event kind of thing.

var store = {
    nextId: 1,
    cache: {},
    add: function(fn) {
        if(!fn.id){
            fn.id = store.nextId++;
            return !!(store.cache[fn.id] = fn);
        }
    }
};

The code works well but now I would like to execute those functions and I haven't been able to figure that part out.

So far I have tried to call the two functions directly as methods of the store.cache object which gives me the error "Object# has no method 'blah'". Also I tried doing a loop as if store.cache was an array of functions but that didn't work either.

Thanks for any help.

Upvotes: 0

Views: 61

Answers (2)

DerWaldschrat
DerWaldschrat

Reputation: 1915

There are easier ways to store a list of callbacks, but to solve your problem just do:

var i;
for (i in store.cache) {
    store.cache[i]();
}

for (i in variable) cycles through all the properties of variable, and i gets the key of the property.

Upvotes: 0

hvgotcodes
hvgotcodes

Reputation: 120178

I would add a method to store, something like this

executeFunction: function(id) {
   var fn = store.cache[id];
   if (fn) return fn();
   else throw 'could not find function for id...';
}

and then you can just do

var result = store.executeFunction(someId);

you can expand upon that so that your executeFunction takes the context (scope) and arguments which should be applied to the function.

Upvotes: 1

Related Questions