[英]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.