-1

In ionic 3 not able to remove device motion event listener. If any solution for this?

window.addEventListener("devicemotion", (evt)=>{
   if(evt.acceleration.x > 10){
      window.removeEventListener("devicemotion"); 
   }
}

Refered link : https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jose G Varanam
  • 767
  • 8
  • 19
  • [Documentation for `.removeEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener) – Pointy Feb 05 '18 at 13:42
  • the .removeEventListener won't work on ionic 3 as the way the documentation. Below I mentioned the answer which worked for me. – Jose G Varanam Mar 05 '18 at 12:04

2 Answers2

0

Finally, I got a solution for Ionic 3

private docEvtDevMotion:EventListenerOrEventListenerObject = null;
private lastX:any = null;

constructor() {

    let self = this;
    this.docEvtDevMotion = (event)=>{
        self.motionDetectionHandler(event);
    }

    this.initMotionDetection();
}

private motionDetectionHandler(event: any) {
        if (!this.lastX) {
            this.lastX = event.acceleration.x;
            this.lastY = event.acceleration.y;
            this.lastZ = event.acceleration.z;
            return;
        }

        let deltaX: number, deltaY: number, deltaZ: number;
        deltaX = Math.abs(event.acceleration.x - this.lastX);
        deltaY = Math.abs(event.acceleration.y - this.lastY);
        deltaZ = Math.abs(event.acceleration.z - this.lastZ);

        // console.error("Motion ====== " + deltaX + " " + deltaY + " " + deltaZ);
        if (deltaX + deltaY + deltaZ > 1) {
            window.removeEventListener("devicemotion", this.docEvtDevMotion, false);
        }

        this.lastX = event.acceleration.x;
        this.lastY = event.acceleration.y;
        this.lastZ = event.acceleration.z;
    }
}

private initMotionDetection(){
   window.addEventListener("devicemotion", this.docEvtDevMotion, false);
}
Jose G Varanam
  • 767
  • 8
  • 19
-1
//motion is your call back function

if (activate) {
    window.addEventListener("devicemotion", motion, true);
    activate = false;
} else {
    window.removeEventListener("devicemotion", motion, true);
    activate = true;
}
venimus
  • 5,907
  • 2
  • 28
  • 38