我还需要创建L.Control
子类L.Evented
。
include: [ L.Mixin.Events ]
有效,但会显示已弃用,我需要继承L.Evented
。但我不能因为我需要继承L.Control
。
我该怎么办?
答案 0 :(得分:2)
你可以将L.Evented自己混合到自定义控件中,如下所示:
var CustomControl = L.Control.extend({
});
L.extend(CustomControl.prototype, L.Evented.prototype);
然后,您可以触发事件并收听它们:
var cc = new CustomControl();
cc.on('myevent', function(s) {
console.log("event fired");
console.log(s);
});
cc.fire('myevent', {})
基于http://leafletjs.com/examples/extending/extending-3-controls.html#controls的演示(单击Leaflet徽标会触发事件)
var map = L.map('map', {
center: [40, 0],
zoom: 1
});
var positron = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
attribution: "CartoDB"
}).addTo(map);
L.Control.Watermark = L.Control.extend({
onAdd: function(map) {
var img = L.DomUtil.create('img');
img.src = 'http://leafletjs.com/docs/images/logo.png';
img.style.width = '200px';
img.addEventListener('click', ()=> {
this.fire('myevent');
});
this.img
return img;
}
});
L.extend(L.Control.Watermark.prototype, L.Evented.prototype);
var mark = new L.Control.Watermark({ position: 'bottomleft' }).addTo(map);
mark.on('myevent', function() {
console.log('clicked');
})

html, body {
height: 100%;
margin: 0;
}
#map {
width: 100%;
height: 150px;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/leaflet.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/leaflet.js"></script>
<div id='map'></div>
&#13;