简体   繁体   English

如何将函数字典分配给 javascript addeventlistener?

[英]how do you assign a dictionary of functions to javascript addeventlistener?

I'm using this book to learn javascript: Secrets of the JavaScript Ninja, Second Edition.我正在使用这本书来学习 javascript:JavaScript 忍者的秘密,第二版。

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.但是这本书没有解释如何将这些函数分配给事件处理程序,一旦它们存储在字典 store.cache 中。

So my question is, how does one assign these functions, straight from the dictionary, into the addEventListener function?所以我的问题是,如何将这些函数直接从字典中分配到 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.'我尝试单独提取函数,例如 store.cache[1].name,但随后弹出一个错误,指出参数不是“对象”类型。 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.我还尝试使用循环来获取 function 名称,但是名称作为字符串返回,并且当名称是字符串时,事件侦听器不会调用函数。 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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM