0

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.

1
  • 1
    The function can be invoked like so: store.cache[1](), store.cache[2](), etc. Commented Aug 7, 2012 at 16:14

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.