【问题标题】:Passing arguments to a callback function in javascript将参数传递给javascript中的回调函数
【发布时间】:2021-08-22 05:41:39
【问题描述】:

我们有这样的场景,我们有多个 <input type="text"/> 框,我们在其中绑定自动建议 (BING MAPS),如下所示。

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

其中“#destination1”或#destination2 是<input type="text"> 元素的ID。 我们有一个函数 selectedAddedDestination,它由 Bing 地图框架调用并接受自动建议的结果。但是,结果不包含哪个<input type="text"> 触发了该事件。

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

我尝试向函数添加属性“pos”。但是,它不可访问。对于每个文本框,我还需要多个具有 'pos' 属性的函数实例,因此也需要函数。

如果有解决办法,请告诉我。

【问题讨论】:

    标签: javascript bing-maps


    【解决方案1】:

    你可以像这样使用 JavaScript closure 做到这一点:

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

    【讨论】:

    • 很棒的解决方案。谢谢!
    猜你喜欢
    • 2011-03-28
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多