如何解决从 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));
我的问题是,来自 window.eventListener 的 this.adjustHeading(event.alpha);
调用不起作用,因为 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 不支持,因此您的最佳选择取决于您需要支持的浏览器。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。