我正在重写我的JS代码,使其更加清晰和准确。我在命名空间中定义了一个模块,并且无法在该绑定函数中传递相同的变量,请参见下面的代码:
// Gmap Autocomplete initialization and reset function
var gMapPlace = gMapPlace || {};
gMapPlace.geoAutocomplete = (function(){
var detail = {
searchEle : null,
autocompleteEle : null,
autocompleteLsr : null,
init : function(searchEle){
this.searchEle = searchEle;
this.autocompleteEle = new google.maps.places.Autocomplete(this.searchEle);
this.autocompleteLsr = google.maps.event.addListener(this.autocompleteEle, 'place_changed', function () {
var data = gMapPlace.geoAutocomplete.data;
// ################################
var place = data.autocompleteEle.getPlace(); // any way to reference simple 'this.autocompleteEle' here
// ################################
var address = place.formatted_address;
var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();
var mesg = "Address: " + address;
mesg += "\nLatitude: " + latitude;
mesg += "\nLongitude: " + longitude;
alert(mesg);
});
},
reset : function(){
if(isNotBlank(this.searchEle)){
google.maps.event.clearInstanceListeners(this.searchEle);
}
}
};
return{
data : detail
};
}());
根据上面的代码,我在this.autocompleteLsr
处有一个绑定函数,该函数在特定事件发生时运行,当我直接使用var place = this.autocompleteEle.getPlace()
时,它会给出undefined
错误运行。现在为了工作,我通过迭代命名空间对象来编写它以获取值,如
var data = gMapPlace.geoAutocomplete.data;
// ################################
var place = data.autocompleteEle.getPlace();// any way to reference simple 'this.autocompleteEle' here
// ################################
有没有其他方法可以在运行时引用模块变量,或者这是唯一的方法。