无法删除设备动作事件侦听器

时间:2018-02-05 13:36:54

标签: javascript javascript-events ionic3 devicemotion

在离子3中无法移除设备动作事件监听器。如果有任何解决方案吗?

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

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

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:-1)

//motion is your call back function

if (activate) {
    window.addEventListener("devicemotion", motion, true);
    activate = false;
} else {
    window.removeEventListener("devicemotion", motion, true);
    activate = true;
}