使用原型模式创建传单地图:onEachFeature 函数出错

Using Prototypal Pattern with Creating a Leaflet Map: error with onEachFeature function

我调用以下代码来创建地图的副本对象,并初始化 Leaflet 地图。这可以正常工作并加载。但是,onEachFeature and/or 和 clickFeature 函数无法正常工作。

var map = {
    mapUrl: "",
    maxZoom: 18,
    minZoom: 2,
    map: L.map('worldMap').setView([51.505, -0.09], 2),
    create: function(values) {
        var instance = Object.create(this);
        Object.keys(values).forEach(function(key) {
        instance[key] = values[key];
        });
        return instance;
    },
    initLeafletMap: function() {
        L.tileLayer(this.mapUrl, {
            attribution: '',
            maxZoom: this.maxZoom,
            minZoom: this.minZoom,
            id: 'mapbox.streets'
        }).addTo(this.map);
        //add continents' outlines
        $.getJSON("/static/continents.json", 
           (function(style, onEachFeature, map) {
                return function(continents) {
                    console.log(typeof(continents));
                    L.geoJson(continents, {
                        style: style,
                        onEachFeature: onEachFeature
                    }).addTo(map);
                };
            }(this.style, this.onEachFeature, this.map))
       );
    },
    style: function() {
        return {
            weight: 2,
            opacity: 1,
            color: 'beige',
            dashArray: '3',
            fillOpacity: 0
        };
    },
    onEachFeature: function(feature, layer) {
        layer.on({
            click: this.clickFeature
        });
    },
    clickFeature: function(e) {
            do something here();
    },

所以当我点击地图时,我知道调用了onEachFeature函数,但它并没有调用clickFeature。相反,我在控制台中收到此错误:

leaflet.js:5 Uncaught TypeError: Cannot read property 'call' of undefined
    at e.fire (leaflet.js:5)
    at e._fireDOMEvent (leaflet.js:5)
    at e._handleDOMEvent (leaflet.js:5)
    at HTMLDivElement.r (leaflet.js:5)

当您将 onEachFeature 方法作为 IIFE 的参数传递时,很可能只需要绑定 this 上下文来构建对 AJAX 调用的回调:

this.onEachFeature.bind(this)

另见

顺便说一句,您还可以将点击事件监听器直接附加到 Leaflet GeoJSON 层组上,而不是为每个子层都这样做。