javascript - Leaflet- 标记点击事件工作正常,但类的方法在回调函数中未定义

标签 javascript ionic-framework onclick leaflet gis

我正在使用以下代码为某些传单标记(我事先不知道其编号)的 click 事件添加回调函数:

newArray.forEach(p => {
  let marker = L.marker(latLng).on('click', this.markerClick).addTo(newMap)
  marker.bindPopup(content)
  marker.addTo(newMap)
  marker.openPopup()
})

类中有函数 markerClick 可以执行此操作:

markerClick(e) {
  console.log("Inside marker click " + e.latlng.lat + "  " + e.latlng.lng)
  this.displayError("You clicked on the marker")
}

console.log 正确打印标记的 latlng 的值,但是在调用 displayError 抛出一个运行时错误说:

this.displayError is not a function

这是在类中声明的一个函数,根据我的需要,我用它来显示带有自定义消息的 toast 。这是代码:

displayError(messageErr: string) {
  let toast = this.toastCtrl.create({
    message: messageErr,
    duration: 3000,
    position: 'top'
  });
  toast.present();
}

为什么说那不是函数?

编辑:不仅仅是displayError,类的每个函数都会给出这个消息。

最佳答案

这是一个典型的 JavaScript 错误。

this在 JavaScript 中不一定引用您的类实例对象。它是函数调用时上下文

您可以使用 bind 强制此上下文,并且在许多库中,您也可以轻松地强制执行它。在这种情况下,使用 Leaflet,您可以将第三个参数传递给 on附加事件监听器时:

// Force current `this` to be the context when `this.markerClick` is called
marker.on('click', this.markerClick, this);

使用 bind 它将是:

marker.on('click', this.markerClick.bind(this));

还有 arrow function解决方案,它使用 this 的上下文/值箭头函数定义的地方,而不是它将被调用的地方:

marker.on('click', (event) => this.markerClick(event));

关于javascript - Leaflet- 标记点击事件工作正常,但类的方法在回调函数中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48170860/

相关文章:

cordova - Ionic 2 应用的 Google Play 应用签名

java - android :onClick use Java reflection concepts behind the scenes?吗

javascript - React App - Chrome 磁盘缓存 JS 文件

javascript - 谁能解释为什么这段代码连接而不是添加数值?

javascript - 在自动脚本中从网站检索 zip 文件

android - 任务 ':app:processDebugResources' 执行失败。在 ionic / Cordova

javascript - Href 在 ion-option-button 中不起作用?

javascript - 如何在AngularJS中使用一个模板和 Controller 进行嵌套路由?

javascript - 单击不触发位置绝对图像

javascript - 点击时,如何让音频一直播放?