转换为匿名函数
Transform to anonymous function
我想将 this example code 转换为函数。我想这样做是因为我在同一页面上有 2 个输入字段,它们必须使用此自动完成功能。我可以像以前那样用旧方法来做这件事,但我想学习一些关于这种编程的知识。这就是我现在拥有的:
var Lookup = {
init: function(field) {
this.field = field;
this.autocomplete = null;
this.autocomplete = new google.maps.places.Autocomplete((document.getElementById(this.field)), {
types: ['geocode']
});
this.autocomplete.addListener('place_changed', this.fillInAddress());
},
geolocate: function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
this.autocomplete.setBounds(circle.getBounds());
});
}
},
fillInAddress: function() {
var place = this.autocomplete.getPlace();
console.log(place);
}
}
我执行这个:
$(document).ready(function () {
Lookup.init('location_from');
Lookup.init('location_to');
});
一切正常,这两个字段具有自动完成功能。但是当我 select 一个地址时,我得到这个错误:
Uncaught TypeError: Cannot read property 'apply' of undefined
这发生在 fillInAddress
函数中。 AJAX 调用被调用(请求该地点的额外详细信息),但随后停止。谁能告诉我这是为什么?
我认为您想为此任务创建一个 jQuery 插件:
$.fn.extend({
geocode: function () {
return this.each(function () {
var ac = new google.maps.places.Autocomplete(this), {
types: ['geocode']
});
ac.addListener('place_changed', function () {
var place = ac.getPlace();
console.log(place);
// ... etc ...
});
});
}
});
和
$('#location_from, #location_to').geocode();
我想将 this example code 转换为函数。我想这样做是因为我在同一页面上有 2 个输入字段,它们必须使用此自动完成功能。我可以像以前那样用旧方法来做这件事,但我想学习一些关于这种编程的知识。这就是我现在拥有的:
var Lookup = {
init: function(field) {
this.field = field;
this.autocomplete = null;
this.autocomplete = new google.maps.places.Autocomplete((document.getElementById(this.field)), {
types: ['geocode']
});
this.autocomplete.addListener('place_changed', this.fillInAddress());
},
geolocate: function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
this.autocomplete.setBounds(circle.getBounds());
});
}
},
fillInAddress: function() {
var place = this.autocomplete.getPlace();
console.log(place);
}
}
我执行这个:
$(document).ready(function () {
Lookup.init('location_from');
Lookup.init('location_to');
});
一切正常,这两个字段具有自动完成功能。但是当我 select 一个地址时,我得到这个错误:
Uncaught TypeError: Cannot read property 'apply' of undefined
这发生在 fillInAddress
函数中。 AJAX 调用被调用(请求该地点的额外详细信息),但随后停止。谁能告诉我这是为什么?
我认为您想为此任务创建一个 jQuery 插件:
$.fn.extend({
geocode: function () {
return this.each(function () {
var ac = new google.maps.places.Autocomplete(this), {
types: ['geocode']
});
ac.addListener('place_changed', function () {
var place = ac.getPlace();
console.log(place);
// ... etc ...
});
});
}
});
和
$('#location_from, #location_to').geocode();