简体   繁体   中英

Need to bind an inner function to the click event of an element

I need to use a "resetMap" function which I defined in my initMap function (callback function for google map), to bind to reset button. Now it cannot be used because its not there in the global scope. If I move this function to global scope its items such as mapOptions.center setzoom etc will be undefined.

This is my script file

var map;

/* Hardcoding 5 airport locations - our data - model*/
var airports = [
    {
        title: "Calicut International Airport",
        lat: 11.13691,
        lng: 75.95098,
        streetAddress: "Karipur",
        cityAddress: "Malappuram, Kerala",
        visible: ko.observable(true),
        id: "nav0",
        showIt: true
    },
    {
        title: "Chennai International Airport",
        lat: 12.9920434,
        lng: 80.1631409,
        streetAddress: "Meenambakkam",
        cityAddress: "Chennai, Tamil Nadu",
        visible: ko.observable(true),
        id: "nav1",
        showIt: true
    },
    {
        title: "Trivandrum International Airport",
        lat: 8.4829722,
        lng: 76.909139,
        streetAddress: "Vallakkadavu",
        cityAddress: "Thiruvananthapuram, Kerala",
        visible: ko.observable(true),
        id: "nav2",
        showIt: true
    },
    {
        title: "Cochin International Airport",
        lat: 10.15178,
        lng: 76.39296,
        streetAddress: "Nedumbassery",
        cityAddress: "Kochi, Kerala",
        visible: ko.observable(true),
        id: "nav3",
        showIt: true
    },
    {
        title: "Kempegowda International Airport",
        lat: 13.2143948,
        lng: 77.6896124,
        streetAddress: "Devanahalli",
        cityAddress: "Bengaluru, Karnataka",
        visible: ko.observable(true),
        id: "nav4",
        showIt: true
    }
];


/* Initializing map, markers */
function initMap() {

    var myLatlng = new google.maps.LatLng(13.2143948, 77.6896124);
    var mapOptions = {
        zoom: 6,
        disableDefaultUI: true
    };

    var bounds = new google.maps.LatLngBounds(
        new google.maps.LatLng(8.4829722, 76.909139), //SW coordinates here
        new google.maps.LatLng(13.2143948, 77.6896124) //NE coordinates here
    );

    map = new google.maps.Map(document.getElementById("map"), mapOptions);
    map.fitBounds(bounds);

    setMarkers(airports);
    setMapWithMarker();

    /* Function to reset the map zoom and set center */
    function resetMap() {
        map.setCenter(mapOptions.center);
        map.setZoom(6);
    }

    $(window).resize(function(){
        map.setCenter(mapOptions.center);
    });
}

/* Controlling the visibility of marker based on the 'showIt' property */
function setMapWithMarker() {
    for (var i = 0; i < airports.length; i++) {
        if(airports[i].showIt === true) {
            airports[i].locMarker.setMap(map);
        } else {
            airports[i].locMarker.setMap(null);
        }
    }
}

/* Setting markers on map and attaching content to each of their info windows */
function setMarkers(location) {
    var img = 'img/airport.png';
    for (var i = 0; i < location.length; i++) {
        location[i].locMarker = new google.maps.Marker({
            position: new google.maps.LatLng(location[i].lat, location[i].lng),
            map: map,
            animation: google.maps.Animation.DROP,
            title: location.title,
            icon:img
        });

        var airportTitle = location[i].title;
        var wikiUrl = 'https://en.wikipedia.org/w/api.php?action=opensearch&search=' +
        airportTitle + '&format=json&callback=wikiCallback';

        (function(i){
            var wikiRequestTimeout = setTimeout(function() {
                $('.show-error').html('ERROR: Failed to load wikipedia data - Airport details will not show up! Sorry for the inconvenience caused.');
            }, 5000);

            $.ajax({
                url: wikiUrl,
                dataType: "jsonp"
            }).done(function(response){
                var article = response[2][0];
                    location[i].contentString =
                    '<strong>'+ location[i].title + '</strong><br><p>' + location[i].streetAddress
                    + '<br>' + location[i].cityAddress + '<br></p><p>' + article +
                    '</p><p>Source: Wikipedia</p>';
                    clearTimeout(wikiRequestTimeout);
            });
        })(i);

        /* info window initialization and setting content to each marker's info window */
        var infowindow = new google.maps.InfoWindow({});

        new google.maps.event.addListener(location[i].locMarker, 'click',
            (function(airport, i) { return function() {
                airport.setAnimation(google.maps.Animation.BOUNCE);
                setTimeout(function() {
                    airport.setAnimation(null);
                }, 2400);
                infowindow.setContent(location[i].contentString);
                infowindow.open(map,this);
                map.setZoom(15);
                map.setCenter(airport.getPosition());
            };
        })(location[i].locMarker, i));

        /* info window call when clicked on airport menu item */
        var searchNav = $('#nav' + i);
        searchNav.click((function(airport, i) {
            return function() {
                airport.setAnimation(google.maps.Animation.BOUNCE);
                setTimeout(function() {
                    airport.setAnimation(null);
                }, 2200);
                infowindow.setContent(location[i].contentString);
                infowindow.open(map,airport);
                map.setZoom(15);
                map.setCenter(airport.getPosition());
            };
        })(location[i].locMarker, i));
    }
}

/* Function for toggling the menu */
function slideToggle() {
    $(this).toggleClass('toggled');
    $( "#listing" ).toggle( "slow", function() {
        // Animation complete.
    });
}

/* Our view model */
function viewModel() {
    var self = this;
    this.locMarkerSearch = ko.observable('');
    ko.computed(function() {
        var search = self.locMarkerSearch().toLowerCase();
        return ko.utils.arrayFilter(airports, function(airport) {
            if (airport.title.toLowerCase().indexOf(search) >= 0) {
                airport.showIt = true;
                return airport.visible(true);
            } else {
                airport.showIt = false;
                setMapWithMarker();
                return airport.visible(false);
            }
        });
    });
};

// Activates knockout.js
ko.applyBindings(new viewModel());

I need to bind the function here in my index.html

<footer>
  <button id="reset" data-bind="click: resetMap">Reset Zoom to center</button>
</footer>

<script src="js/lib/knockout-3.4.0.js"></script>
<script src="js/script.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDVOVW9WT7QaVlFYDkE7K2Qm-AvSS02YrM&callback=initMap" async defer onerror="googleError()"></script>

How can I resolve this problem? Thanks in advance..

You haven't shown us how viewModel uses initMap , but fundamentally, initMap needs to make resetMap available to the outside world. One way to do that is to return it:

function initMap() {
    // ...
    function resetMap() {
    }
    // ...
    return resetMap;
}

and then have code in viewModel put that on the view model:

function viewModel() {
    this.resetMap = initMap(); // I assume you're calling this indirectly; whatever
}

Then resetMap has access to what it needs, and it's on the view model so it can be bound.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM