首页 > 解决方案 > 添加使用对象方法的单击事件处理程序

问题描述

我正在尝试为传单构建一个包装 JavaScript 类。我需要将点击事件绑定到地图(以及弹出窗口内的按钮旁边),老实说,我不知道该怎么做。

我根本无法运行类方法 selectorClick()。我还需要能够将参数传递给它。

代码:https ://codepen.io/hendr1x/pen/GRKLjrW

class Map {
    self = this;
    name = '';
    elem;
    theme = 'http://b.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png';

    constructor(name) {
        self.name = name;
        self.elem = L.map(name).fitWorld().zoomIn();
        L.tileLayer(this.theme, {
            attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors',
            maxZoom: 18,
        }).addTo(self.elem);
    }

    selector(url, message) {
        self.elem.on("click", self.selectorClick(url, message));
    }

    selectorClick(url, message) {
        alert(message);
    }
}
var mapMap = new Map('map');
mapMap.selector('/index.php', 'test message');

编辑

让我解释一下,我提供的示例从我的实际情况中消除了很多复杂性,因为我在数据服务器上存储了很多。因此,对于我们目前正在查看的内容,我的控制器中有类似的东西

$this->c->map->init('mapElem');
$this->c->map->selector('/example/submit/index.php', 'You clicked this example');

which eventually echo's the following

echo "window." . $name . "Map = new Map('" . $name . "');";
echo $name . "Map.selector('" . $url . "', '" . $message . "');";

因此,考虑到这一点,我试图通过外部 js 文件运行尽可能多的代码,并在我使用它时发送所有动态值(就像我上面所做的那样)。因此,要回答您的问题,我需要传入 url 和消息,这样当地图被点击时,我就有了正确创建弹出窗口的数据。

标签: javascriptoopleaflet

解决方案


有很多方法可以处理这样的事情。这一切都取决于你想要完成的事情。

您想将哪些参数传递给该selectorClick方法?你想用什么来完成selectorClick

class Map {
  constructor(id) {
    this.elem = L.map(id).fitWorld().zoomIn();
    this.name = id;
    this.theme = "http://b.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png";
    this.url = "";
    this.message = "";
    
    this.selectorClick = this.selectorClick.bind(this);
    this.elem.on("click", this.selectorClick);
    
    L.tileLayer(this.theme, {
      attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors',
      maxZoom: 18
    }).addTo(this.elem);
  }
  
  selector(url, message) {
    this.url = url;
    this.message = message;
  }

  selectorClick(event) {//<--- event is automatically passed in because of the 'onclick' handler
    let location = event.latlng;
    alert(`POST DATA HERE:\n\n${JSON.stringify(location, null, 2)}`)
  }
}

const mapMap = new Map("map");
mapMap.selector("/index.php", "test message");
#map { height: 180px; }
<html>

<head>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" />
  <script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js" integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og==" crossorigin=""></script>
</head>

<body>
  <div style="text-align:center;">
    <h2>Click Anywhere On Map</h2>  
  </div>
  <div id="map"></div>
  </div>
</body>

</html>


推荐阅读