我正在尝试使用jQuery UI自动填充功能来制作Google自动填充服务的包装器(因为我只想以Google API无法实现的方式限制Google返回的部分结果)。
假设我有这段代码:
$("#address").autocomplete({
source: function(request, response){
autoCompleteService = new google.maps.places.AutocompleteService();
autoCompleteService.getQueryPredictions({input: request.term }, autocompleteCallback);
//I should somewhere call the "response" object with desired suggestions as arguments
},
minLength: 5,
});
问题是jQuery UI Autocomplete迫使我调用“响应”对象(实际上是一个函数),并将我想要作为参数显示给用户的建议。
但是,另一方面,Google API强制我定义一个回调函数(在我的情况下是'autocompleteCallback'),它在完成后将请求的建议作为参数提供给他们。
当然,我不能在'autocompleteCallback'函数中调用'response'对象,我也不能在这行之后调用响应对象:
autoCompleteService.getQueryPredictions({input: request.term }, autocompleteCallback);
因为JS是异步的,我不能确定我得到的东西就是说:我用来传递结果的全局变量。
那会有什么解决方案? 对于像这样的问题,有一个众所周知的JS设计模式吗?
答案 0 :(得分:7)
先生,你是结合这两个框架的天才!所以我将分享我的解决方案:
$("#search").autocomplete({
source: function (request, response) {
autoCompleteService.getQueryPredictions({ input: request.term }, function (predictions, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
response($.map(predictions, function (prediction, i) {
return {
label: prediction.description,
value: prediction.description
}
}));
});
},
select: function (event, ui) {
var value = ui.item.value;
searchMap(value);
}
});
当然,我有一个实际的函数可以进行正确的Place查找(searchMap()
)。为了使jQuery UI自动完成具有适当的autocompleteCallback
AND response
处理程序,唯一可行的方法是使回调实现保持内联。如果你想在不止一个地方做这件事很糟糕,但我没有想到更好的事情。然而...