I'm using this book to learn javascript: Secrets of the JavaScript Ninja, Second Edition.
In the book, there is code to store functions in a dictionary as a way to manage multiple functions in an event handler.
var store = {
nextId: 1,
cache: {},
add: function(fn){
if (!fn.id) {
fn.id = this.nextId++;
this.cache[fn.id] = fn;
return true;
}
}
}
store.add(myFunction1);
store.add(myFunction2);
store.add(myFunction3);
But the book doesn't explain how to assign these functions to an event handler once they are stored the the dictionary store.cache.
So my question is, how does one assign these functions, straight from the dictionary, into the addEventListener function? I tried pulling the functions out individually, such as store.cache[1].name, but then an error pops up saying the parameter is not of type 'Object.' I also tried to use a loop to get the function names, but the names come back as strings and the event listener doesn't call the functions when the names are strings. What am I missing here? Thank you in advance!
You can refer to them by their numerical order in the array. Then still pass any parameters as needed.
let myFunction1 = function(p) {
console.log(p)
}
var store = {
nextId: 1,
cache: {},
add: function(fn) {
if (!fn.id) {
fn.id = this.nextId++;
this.cache[fn.id] = fn;
return true;
}
}
}
store.add(myFunction1);
store.cache[1]("x");