-1

在 ionic 3 中无法删除设备运动事件侦听器。如果有任何解决方案?

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

参考链接:https ://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent

4

2 回答 2

0

最后,我得到了 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);
}
于 2018-02-07T02:52:28.763 回答
-1
//motion is your call back function

if (activate) {
    window.addEventListener("devicemotion", motion, true);
    activate = false;
} else {
    window.removeEventListener("devicemotion", motion, true);
    activate = true;
}
于 2018-02-06T04:34:21.787 回答