【发布时间】:2016-06-28 15:04:51
【问题描述】:
目标
我想去掉匿名函数调用带来的重复代码。
背景
我正在做一个非常简单的项目,我使用 Google Maps API 显示带有两个搜索框的地图。用户在这些框中输入起始地址和结束地址,然后我在地图中显示标记。
为了实现这一点,我为侦听器设置了两个匿名函数,除了一点之外,它们完全相等 - 一个使用 startSearchBox,另一个使用 endSearchBox。
我尝试了什么
这种代码重复是不必要的,因此我尝试将搜索框作为参数传递给匿名函数,但没有奏效。
我还考虑将搜索框创建为全局变量,但我希望避免这种做法。
我怎样才能消除这段代码中的重复?
代码
function initSearchBoxes() {
// Create the search box and link it to the UI element.
let startInput = document.getElementById('start-input');
let startSearchBox = new google.maps.places.SearchBox(startInput);
let endInput = document.getElementById('end-input');
let endSearchBox = new google.maps.places.SearchBox(endInput);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
startSearchBox.setBounds(map.getBounds());
endSearchBox.setBounds(map.getBounds());
});
startSearchBox.addListener('places_changed', function() {
deleteAllMarkers();
let places = startSearchBox.getPlaces();
if (places.length == 0) {
return;
}
// For each place, get the icon, name and location.
let bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
// // Create a marker for each place.
let newMarker = createMarker(place.geometry.location, place.name, markerLabels.nextSymbol(), true);
markerLib.trackMarker(newMarker);
newMarker.setMap(map);
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
}
else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
endSearchBox.addListener('places_changed', function() {
deleteAllMarkers();
let places = endSearchBox.getPlaces();
if (places.length == 0) {
return;
}
// For each place, get the icon, name and location.
let bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
// // Create a marker for each place.
let newMarker = createMarker(place.geometry.location, place.name, markerLabels.nextSymbol(), true);
markerLib.trackMarker(newMarker);
newMarker.setMap(map);
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
}
else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
【问题讨论】:
标签: javascript google-maps listener anonymous-function code-duplication