简体   繁体   中英

AddEventListener dynamic function reference to anonymous function

So I have a function and I want to be able to create and remove the function with a reference to an anonymous function. I want to do this to provide the ability to create the same function for multiple object. Currently when I create one function and then create another I believe it is overwriting the reference with the newest one and that does not allow me to remove the older reference.

So I want to dynamically create the reference with a variable with something like this.

image.addEventListener("click", 
    (Highlight + image.alt) = function (){ HighLightClick(this) }, false);

and then remove it like this

TileClicked.removeEventListener("click", (Highlight + TileClicked.alt), false);

Do I have to create a variable for TileClicked or how would one go about this?

Maybe something like:

var functionMap = {};

funtionMap[Highlight + image.alt] = function (){ HighLightClick(this) };
image.addEventListener("click", funtionMap[Highlight + image.alt], false);

TileClicked.removeEventListener("click", funcionMap[Highlight + TileClicked.alt], false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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