JavaScript中如何为Bing Maps AutoSuggest回调传参识别触发输入
问题根因
你当前的写法不生效的核心原因是:Function.prototype.bind 会返回一个全新的函数实例,你给这个新实例添加了pos属性,但回调逻辑中访问的是外层定义的原始selectedAddedDestination函数对象,两个不是同一个实例,自然读取不到对应的属性值。
可行解决方案
方案1:闭包捕获索引(最推荐)
不需要额外给函数挂载属性,直接利用闭包的特性存储每个输入框对应的索引,逻辑最简洁,也没有上下文冲突问题。
首先调整回调函数为高阶函数,接收索引参数,返回实际执行的回调逻辑:
function selectedAddedDestination(destinationIndex) { // 返回的函数会被Bing Maps调用,闭包会捕获外层的索引值 return function(suggestionResult) { const position = destinationIndex; map.entities.clear(); map.setView({ bounds: suggestionResult.bestView }); // 其余原有逻辑 } }
再修改绑定部分的代码:
Microsoft.Maps.loadModule('Microsoft.Maps.AutoSuggest', function () { var options = { maxResults: 4, map: map }; var manager = new Microsoft.Maps.AutosuggestManager(options); // 传入当前索引,得到对应绑定了索引的回调实例 var callback = selectedAddedDestination(destinationIndex); manager.attachAutosuggest('#destination'+destinationIndex, '#divAddDestination', callback); });
提示:如果你的
destinationIndex是循环中用var声明的变量,请将循环变量改为let声明,避免所有闭包捕获到同一个变量的问题。
方案2:利用bind绑定的this上下文存值
你之前调用bind时传入了空对象,可以直接把索引存在这个绑定的this对象上,不需要修改回调的结构:
绑定部分修改如下:
Microsoft.Maps.loadModule('Microsoft.Maps.AutoSuggest', function () { var options = { maxResults: 4, map: map }; var manager = new Microsoft.Maps.AutosuggestManager(options); // 把索引直接挂载到bind绑定的this对象上 var callback = selectedAddedDestination.bind({pos: destinationIndex}); manager.attachAutosuggest('#destination'+destinationIndex, '#divAddDestination', callback); });
回调函数直接读取this.pos即可:
function selectedAddedDestination(suggestionResult) { var position = this.pos; map.entities.clear(); map.setView({ bounds: suggestionResult.bestView }); // 其余原有逻辑 }
方案3:修改取值逻辑读取当前函数实例属性
如果你要保留给函数实例加属性的写法,只需要调整回调中读取属性的方式,获取当前正在执行的函数实例即可(仅支持非严格模式):
function selectedAddedDestination(suggestionResult) { // arguments.callee指向当前正在执行的函数实例,也就是你加了pos属性的bind返回的函数 var func = arguments.callee; var position = func['pos']; map.entities.clear(); map.setView({ bounds: suggestionResult.bestView }); // 其余原有逻辑 }
内容的提问来源于stack exchange,提问作者Balaji
相关产品推荐
相关产品推荐

