简体   繁体   English

将 arguments 传递给 javascript 中的回调 function

[英]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.我们有这样的场景,我们有多个<input type="text"/>框,我们在其中绑定自动建议(BING 地图),如下所示。

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.其中 '#destination1" 或 #destination2 是<input type="text">元素的 ID。我们有一个 function selectedAddedDestination,它由 Bing Maps 框架调用并接受自动建议的结果。但是,结果不包含<input type="text">触发了事件。

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.我尝试将属性“pos”添加到 function。但是,它不可访问。 I also need multiple instances of function with 'pos' property for each text box, and hence the function.我还需要 function 的多个实例,每个文本框都带有“pos”属性,因此需要 function。

Please let me know if there is a solution to this.如果有解决方案,请告诉我。

You could do that with a JavaScript closure like this:你可以像这样使用 JavaScript 闭包来做到这一点:

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
  };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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