javascript - 从外部 window.EventListener 调用函数
问题描述
所以我试图在我之外调用一个函数
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));
我的问题是,this.adjustHeading(event.alpha);
来自 window.eventListener 的调用不起作用,因为 adjustHeading() 在 windows 范围内不可用。
有什么方法可以绕过它并访问同一文件中的 JS 属性?
我正在为地图视图使用 smyfony 和 openlayers,如果这有帮助的话。
解决方案
问题是因为您的代码期望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 中不支持,所以对你来说最好的选择归结为你需要支持哪些浏览器。
推荐阅读
- android - 使用 Fetch 库 Android 为组下载显示单个 ProgressBar
- javascript - 如何将按钮放在输入字段中?
- python - 如何在 python 中加载 Electron + EEL
- wpf - 自定义 WPF DataGrid 从 ViewModel 中手动选择一行或多行
- html - 如何迭代对象以在 Angular 中打印这种类型的 UI?
- pandas - 熊猫读取 sql 不返回所有行
- xamarin.forms - 在使用 proguard 缩小 apk 大小时出现错误,因为“java.exe”以代码 1 退出
- amazon-web-services - 如何在 GCP/Azure/AWS 中创建可以通过浏览器访问的 Linux VM
- python - Python 2.7 和 3.9,Windows 10,`%USERPROFILE%\AppData\Roaming\` 中的不同结构 && 验证 Python 2.7 的 env-var 路径
- bash - 尝试转义双引号时显示单引号的变量