【问题标题】:Calling function from outside window.EventListener从外部 window.EventListener 调用函数
【发布时间】:2021-05-31 23:00:07
【问题描述】:

所以我试图在我之外调用一个函数

window.addEventListener('deviceorientation', function (event) {
            console.log(event.alpha + ' : ' + event.beta + ' : ' + event.gamma);
            this.adjustHeading(event.alpha);
        })

我试图调用的函数:

adjustHeading: function (heading) {
        this.map.getModel().setViewRotation(heading, false);
    }

整个js:

(function ($) {
'use strict';

$.widget("symfony.GpsPosition", {

    //lots of code//

    listenForDeviceOrientation: function() {
       window.addEventListener('deviceorientation', function (event) {
            console.log(event.alpha + ' : ' + event.beta + ' : ' + event.gamma);
            this.adjustHeading(event.alpha);
        })},

    adjustHeading: function (heading) {
        this.map.getModel().setViewRotation(heading, false);
    }
});

}(jQuery));

我的问题是,来自 window.eventListener 的 this.adjustHeading(event.alpha); 调用不起作用,因为在 windows 范围内adjustHeading() 不可用。

有什么方法可以绕过它并访问同一文件中的 JS 属性?

我正在为地图视图使用 smyfony 和 openlayers,如果这有帮助的话。

【问题讨论】:

标签: javascript jquery symfony openlayers device-orientation


【解决方案1】:

问题是因为您的代码期望事件处理函数中的this 是对您提供给$.widget 的设置对象的引用。但是,在事件处理程序中,范围已更改,因此 this 指的是您将事件附加到的对象,在本例中为 window

要解决此问题,您可以使用 ES6 箭头函数来定义事件处理程序,因为它们不会影响处理程序的范围:

listenForDeviceOrientation: () => window.addEventListener('deviceorientation', e => this.adjustHeading(e.alpha)),
adjustHeading: heading => this.map.getModel().setViewRotation(heading, false);

或者,您也可以将this 引用“缓存”在外部作用域中声明的变量中,以便在事件处理程序中使用:

$.widget("symfony.GpsPosition", {
  let _this = this;
    
  // lots of code...

  listenForDeviceOrientation: function() {
    window.addEventListener('deviceorientation', function(event) {
      _this.adjustHeading(event.alpha);
    })
  },
  adjustHeading: function(heading) {
    _this.map.getModel().setViewRotation(heading, false);
  }
});

前者更简洁,但IE不支持,所以对你来说最好的选择是你需要支持的浏览器。

【讨论】:

    猜你喜欢
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 2014-10-01
    • 2015-03-02
    • 2019-12-13
    • 2011-07-05
    • 1970-01-01
    相关资源
    最近更新 更多