如何在谷歌地图监听器中使用布尔值

How to use bool in Google maps listener?

本文关键字:布尔值 监听器 谷歌地图      更新时间:2023-09-26

我在这个问题上停了 4 小时,if在调用谷歌地图事件时忽略了我的布尔值。我需要在参数中提供不同的数据。也许世界上有人知道为什么?

console.log 同时点击后抛出:

true before click
stack.html:56[object HTMLDivElement]in listener
stack.html:62[object HTMLDivElement]bunga bunga

破碎的布尔值:

this.b = true;
...
console.log(this.b + " beafore click");
this.mapListener = google.maps.event.addListener(map, 'click', function(e) {
    console.log(this.b + "in listener");
    if (this.b==true) {
        console.log(this.b + "true works");
        tools[type](e.latLng, last_marker_origin);
        this.b = false;
    } else {
        console.log(this.b + "bunga bunga");
        //tools[type](e.latLng);
    }
});

this引用我的对象默认值设置为 false 中的"属性",但当我更改选项时,它被标记为 true。

我现在去睡觉了。我会在早上回答。

您的问题是this不再是对您的properties的有效引用。处理特定问题的最简单方法是更改代码:

this.b = true;
var props = this;
console.log(this.b + " beafore click");  //Notice that "this" is still valid here 
this.mapListener = google.maps.event.addListener(map, 'click', function(e) {
    console.log(props.b + "in listener");
    if (props.b == true) {
        console.log(props.b + "true works");
        tools[type](e.latLng, last_marker_origin);
        props.b = false;
    } else {
        console.log(props.b + "bunga bunga");
        //tools[type](e.latLng);
    }
});

根本问题是实际调用回调函数的代码位于完全不同的范围内,因此当代码运行时,this的含义已更改。设置引用并将其放入代码中将解决您的问题。

这里的问题是this的范围。当您在单击事件处理程序函数中时this不再引用属性对象,而是引用事件处理程序。事件处理程序是所谓的闭包。

对于您的问题,有两种可能的解决方案。

  1. 使用局部变量(var b而不是this.b)作为你的值,局部变量被复制到闭包中,因此该值可以在闭包内外使用:

    var b = true;
    console.log(b + " beafore click");
    this.mapListener = google.maps.event.addListener(map, 'click', function(e) {
        console.log(b + "in listener");
        if (b==true) {
            console.log(b + "true works");
            tools[type](e.latLng, last_marker_origin);
            b = false;
        } else {
            console.log(b + "bunga bunga");
            //tools[type](e.latLng);
        }
    });
    
  2. this保存在局部变量中,这是避免作用域问题的非常常见的技术:

    //save this in a locale variable, now 'me' provides access to this scope
    var me = this;
    me.b = true;
    console.log(me.b + " beafore click");
    this.mapListener = google.maps.event.addListener(map, 'click', function(e) {
        console.log(me.b + "in listener");
        if (me.b==true) {
            console.log(me.b + "true works");
            tools[type](e.latLng, last_marker_origin);
            me.b = false;
        } else {
            console.log(me.b + "bunga bunga");
            //tools[type](e.latLng);
        }
    });