iceblender
iceblender

Reputation: 59

event listeners compounding after each page refresh

So I used this tutorial to build a custom right click menu for some graphs: https://www.sitepoint.com/building-custom-right-click-context-menu-javascript/

It's working great, but I have one problem with the listeners. Specifically, when contextListeners and clickListeners functions are called, event listeners are added when the page loads. However, in my application, I have a button which redraws these graphs and reloads the page that the custom right click menu is attached to, and every time, new listeners are created. As a result, the function associated with the right click menu is called twice if I load two different graphs, and thrice if I load it three times. Here's the function that keeps getting called, and keeps adding listeners

function contextListener() {
                        document.addEventListener("contextmenu", function(e) {
                            taskItemInContext = clickInsideElement(e, taskItemClassName);
                            if (taskItemInContext) {
                                e.preventDefault();
                                toggleMenuOn();
                                positionMenu(e);
                            } else {
                                taskItemInContext = null;
                                toggleMenuOff();
                            }
                        });
                    }

and in a later function I tried:

document.removeEventListener("contextmenu", function(e) {
                            console.log("removed");
                        });

but that doesn't seem to do the trick.

Upvotes: 0

Views: 963

Answers (1)

xiaoqian
xiaoqian

Reputation: 71

i don`t understand you question well ,but you can try this :

function contextListener() {
                if(!document.handAddcontext){
                    document.handAddcontext = true
                    document.addEventListener("contextmenu", function(e) {
                        taskItemInContext = clickInsideElement(e, taskItemClassName);
                        if (taskItemInContext) {
                            e.preventDefault();
                            toggleMenuOn();
                            positionMenu(e);
                        } else {
                            taskItemInContext = null;
                            toggleMenuOff();
                        }
                    });
                }

                }

Upvotes: 1

Related Questions