简体   繁体   中英

Passing arguments to a callback function in javascript

We have this scenario where we have multiple <input type="text"/> boxes where we bind auto-suggest (BING MAPS) as below.

Microsoft.Maps.loadModule('Microsoft.Maps.AutoSuggest', function () {
            var options = {
                maxResults: 4,
                    map: map
            };
            var manager = new Microsoft.Maps.AutosuggestManager(options);
                            
            var callback = {
                    selectedAddedDestination : selectedAddedDestination.bind({})
            }
                            
            callback.selectedAddedDestination['pos'] = destinationIndex;
                            
            manager.attachAutosuggest('#destination'+destinationIndex+'', '#divAddDestination', callback.selectedAddedDestination);
                            
        });

where '#destination1" or #destination2 is the id of the <input type="text"> element. We have a function selectedAddedDestination, which is called by Bing Maps framework and accepts the auto suggested results. However, the result does not contain which <input type="text"> fired the event.

function selectedAddedDestination(suggestionResult) {
                        
        var func = selectedAddedDestination;
        var position = func['pos']
        map.entities.clear();
        map.setView({ bounds: suggestionResult.bestView });
        ........
}

I tried adding a property 'pos' to the function. However, it is not accessible. I also need multiple instances of function with 'pos' property for each text box, and hence the function.

Please let me know if there is a solution to this.

You could do that with a JavaScript closure like this:

Microsoft.Maps.loadModule("Microsoft.Maps.AutoSuggest", function () {
  var options = {
    maxResults: 4,
    map: map,
  };
  var manager = new Microsoft.Maps.AutosuggestManager(options);

  manager.attachAutosuggest(
    "#destination" + destinationIndex + "",
    "#divAddDestination",
    selectedAddedDestination(destinationIndex)
  );
});

function selectedAddedDestination(destinationIndex) {
  return function (suggestionResult) {
    map.entities.clear();
    map.setView({ bounds: suggestionResult.bestView });
    // Do what you want with destinationIndex
  };
}

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