【问题标题】:How to remove duplicated function in javascript listener?如何删除javascript监听器中的重复函数?
【发布时间】: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


    【解决方案1】:

    您可以将回调函数包装在另一个“工厂”函数中。工厂将获取一个参数(搜索框引用),然后它会返回实际的处理程序:

    function makeSearchHandler(searchBox) {
        return function() {
    
            deleteAllMarkers();
    
            let places = searchBox.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);
        };
    }
    

    该函数包含原始代码,但不是直接引用startSearchBoxendSearchBox,而是使用传递给工厂的参数。因此,返回的函数将像您的那样工作,但代码只出现一次。

    然后您可以使用该函数来创建回调:

    startSearchBox.addListener('places_changed', makeSearchHandler(startSearchBox));
    endSearchBox.addListener('places_changed', makeSearchHandler(endSearchBox));
    

    【讨论】:

    • 整洁!没想到,谢谢!
    • @Flame_Phoenix 在很多情况下它都是一种有用的方法。祝你好运!
    猜你喜欢
    • 2020-03-17
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    • 2020-06-20
    • 2014-09-29
    • 2023-02-07
    相关资源
    最近更新 更多