0

I have this code:

grabbale.addEventListener("leap-hand-grab", function(e){
if (e.state === "grab") {
            console.log("grabbed");
} else if (e.state === "release") {
            console.log("release");
} else if (e.state === "move") {
    if (stopGrab == 0) {
        grabbale.style.left = e.x - (grabbale.offsetWidth/2)+ "px";
        grabbale.style.top = e.y - (grabbale.offsetHeight/2)+ "px";
    } else {
        $("#foo").css({
        "color": "red"
        });
    }
}

})

what I need is to remove eventListener using removeEventListener, but it require two arguments, the event and the function. In my case the function haven't a name, and the event is the drag of grabbale element... How can I do what I need?

2 Answers2

1

Well you can usea a named function instead, which is the same thing only the anonymous function now has a name.

grabbale.addEventListener("leap-hand-grab", grabListener);

function grabListener(e){
    if (e.state === "grab") {
        console.log("grabbed");
    } else if (e.state === "release") {
        console.log("release");
    } else if (e.state === "move") {
        if (stopGrab == 0) {
            grabbale.style.left = e.x - (grabbale.offsetWidth/2)+ "px";
            grabbale.style.top = e.y - (grabbale.offsetHeight/2)+ "px";
    } else {
        $("#foo").css({
        "color": "red"
        });
    }
}

And for removal just use

grabbale.removeEventListener("leap-hand-grab", grabListener);

Where you need to remove the event.

Some extra links:

Crisoforo Gaspar
  • 3,740
  • 2
  • 21
  • 27
0
grabbale.addEventListener("leap-hand-grab", react);
function react(e){
  if (e.state === "grab") {
        console.log("grabbed");
   } else if (e.state === "release") {
        console.log("release");
   } else if (e.state === "move") {
  if (stopGrab == 0) {
    grabbale.style.left = e.x - (grabbale.offsetWidth/2)+ "px";
    grabbale.style.top = e.y - (grabbale.offsetHeight/2)+ "px";
    grabbale.removeEventListener("leap-hand-grab",react);
 } else {
    $("#foo").css({
    "color": "red"
    });
    }
  }
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151