我今天只是在学习揭示模块模式,到目前为止我做得还不错。但是我想知道当一个显示模块模式函数从另一个显示模块模式中调用时,你可以返回一个值给调用者模式函数吗?
例如,我有一个包含多个功能的位置模块模式,我希望使用另一个模块模式。这是它的代码:
位置显示模块模式
// Revealing Modular pattern, containing functions relevant to location functionality
var Location = (function(window, undefined){
// Gets co-ordinates of users current position (TRUE: Run geoLocate function, FALSE: Run geoError function)
function getCoords(){
navigator.geolocation.getCurrentPosition(getLocation, provideError);
}
// Get users current location
function getLocation(position){
var lat = position.coords.latitude;
var lng = position.coords.longitude;
// Convert seperate variables into one string type variable (Google geocode expects string format)
var myLocation = String(lat+","+lng);
console.log(myLocation);
}
// Error handler for geolocation
function provideError(error){
console.log(error);
}
// Explicitly return public methods when this object is instantiated
return{
getUserLocation : getCoords
};
})(window);
在我的另一个揭示模块模式(如下)中,我正在调用 getUserLocation 函数(又名 getCoords),目前,它 console.logs 用户位置(myLocation)。
// Revealing Modular pattern, containing functions relevant to park functionality
var Park = (function(window, undefined){
// Determine if user entered postcode or selected 'use my location'
function handleUserData(data){
if(data === "postcode"){
var location = document.getElementById("postcode").value;
}
else{
var location = Location.getUserLocation();
}
}
// Explicitly return public methods when this object is instantiated
return{
handleMe : handleUserData
};
})(window);
但是,当我更改 console.log(myLocation) 以返回 myLocation,然后返回控制台日志位置(在函数 handleUserData 中)时,我得到未定义。
我的理论是我想获取用户的位置,然后在 Park 显示模块模式函数中使用它。
所以我的问题是,是否可以将一个显示模块模式的值返回到另一个?如果没有,我应该研究其他方法来帮助我解决我的问题吗?
编辑
根据评论中的帮助,我能够使用以下方法解决此问题:
地点
// Revealing Modular pattern, containing functions relevant to location functionality
var Location = (function(window, undefined){
// Gets co-ordinates of users current position (TRUE: Run geoLocate function, FALSE: Run geoError function)
function getCoords(callback){
navigator.geolocation.getCurrentPosition(
function(position){
var lat = position.coords.latitude;
var lng = position.coords.longitude;
// Convert seperate variables into one string type variable (Google geocode expects string format)
var myLocation = String(lat+","+lng);
callback(myLocation);
}
)
}
// Explicitly return public methods when this object is instantiated
return{
getUserLocation : getCoords
};
})(window);
公园
// Revealing Modular pattern, containing functions relevant to park functionality
var Park = (function(window, undefined){
// Determine if user entered postcode or selected 'use my location'
function handleUserData(data){
var location;
if(data === "postcode"){
location = document.getElementById("postcode").value;
}
else{
Location.getUserLocation(function(userLocation){
location = userLocation;
console.log(location);
});
}
}
// Explicitly return public methods when this object is instantiated
return{
handleMe : handleUserData
};
})(window);