[英]Typescript passing Function as parameter
我試圖傳遞兩個函數作為參數,以便為Leaflet貼圖自定義圖層可視化。 除了特定情況外,在我要求更籠統的概念時,在這里可能不相關,我所做的是:
Map.createLayer(function onEachFeature(feature, layer) {
var popupContent = "<p>I started out as a GeoJSON " +
feature.geometry.type + ", but now I'm a Leaflet vector!</p>";
if (feature.properties && feature.properties.popupContent) {
popupContent += feature.properties.popupContent;
}
layer.bindPopup(popupContent);
},
function pointToLayer(feature, latlng) {
return L.circleMarker(latlng, {
radius: 8,
fillColor: "#ff7800",
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
})
});
Map(包裝Leaflet Map)的方法“ createLayer”在哪里:
public createLayer(popupContent:(feature, layer) => void, renderPoint:(feature,latlng) => L.CircleMarker): ICOLayer{
this.layer = L.geoJSON(this.datasource.get(), {
style: function(feature) {
return feature.properties && feature.properties.style;
},
onEachFeature: popupContent,
pointToLayer: renderPoint
});
return this;
}
這不起作用,我也不知道為什么,但是如果我將它們作為匿名函數傳遞(從而忽略了輸入參數),則一切正常:
public createLayer(popupContent:(feature, layer) => void, renderPoint:(feature,latlng) => L.CircleMarker): ICOLayer{
this.layer = L.geoJSON(this.datasource.get(), {
style: function(feature) {
return feature.properties && feature.properties.style;
},
onEachFeature: function onEachFeature(feature, layer) {
var popupContent = "<p>I started out as a GeoJSON " +
feature.geometry.type + ", but now I'm a Leaflet vector!</p>";
if (feature.properties && feature.properties.popupContent) {
popupContent += feature.properties.popupContent;
}
layer.bindPopup(popupContent);
},
pointToLayer: function pointToLayer(feature, latlng) {
return L.circleMarker(latlng, {
radius: 8,
fillColor: "#ff7800",
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
})
}
});
return this;
}
我也嘗試過刪除輸入中函數的簽名,將它們作為純變量傳遞,但是它不起作用,我對javascript / typescript不熟悉,因此這可能是一個愚蠢的錯誤。 請原諒我。
編輯:執行第一種方法時未顯示任何錯誤消息
在這兩種情況下,您似乎都具有完全相同的代碼。 我在這里可以想象的一個問題-范圍問題。 L.circleMarke
( 在第一個示例中具有代碼塊時 )未定義L
變量。 但是將代碼移到createLayer
方法所在的模塊中-我假設您從導入中獲得了L
引用。
第二個問題是,為什么您沒有對未定義的L
產生異常。 我可以假設在代碼中的某個地方有一條try..catch
語句,該語句吞噬了異常。
在chrome上運行代碼,並打開開發人員工具,並pause on caught exceptions
選項上處於pause on caught exceptions
狀態。
同樣,您可以在兩種情況下將斷點放置在函數內部,以確保調用了這些函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.