我对Meteor很新,但到目前为止,我真的很享受平台上的编码。我遇到了一些障碍,似乎无法找到正确的方法。我想创建一个辅助函数,它将检查lat和long并在某个预定义范围内检查它,如果它介于它们之间则返回true。
我已经包含了我目前的代码:
Template.header.helpers({
locationCheck: function() {
navigator.geolocation.getCurrentPosition(success_callback,error_callback);
function success_callback(p){
// Building Latitude = 51.522206
// Building Longitude = -0.078305
var lat = parseFloat(p.coords.latitude);
var lon = parseFloat(p.coords.longitude);
console.log('Latitude: '+lat);
console.log('Longitiude: '+lon);
if( lat >= 51.521606 && lat <= 51.522606 && lon >= -0.078805 && lon <= -0.077705 ) {
console.log('you are in the area');
return 1;
} else {
console.log('you are not in the area');
return 0;
}
}
function error_callback(p){
return 0;
}
}
});
在我的模板中,我想在句柄if if语句中使用返回值,如下所示:
{{#if locationCheck}}
{{loginButtons}}
{{else}}
<p>Your are out of the vicinity</p>
{{/if}}
问题是它始终返回else语句结果,即使在控制台中它返回此you are in the area
。
任何帮助都会很棒。
提前致谢。
答案 0 :(得分:3)
这是因为回调模式。在回调返回数据时,帮助程序已经返回undefined。您需要在帮助程序中使用同步javascript,如果进行异步操作,请使用reactive Meteor Session
hashes通过以下方式中继数据:
Template.header.helpers({
locationCheck: function() {
return Session.get("locationCheck");
},
isLoading:function() {
return Session.equals("locationCheck",null);
}
});
然后在模板为created的标题中,您可以触发检查:
Template.header.created = function() {
navigator.geolocation.getCurrentPosition(success_callback,error_callback);
function success_callback(p){
// Building Latitude = 51.522206
// Building Longitude = -0.078305
var lat = parseFloat(p.coords.latitude);
var lon = parseFloat(p.coords.longitude);
console.log('Latitude: '+lat);
console.log('Longitiude: '+lon);
if( lat >= 51.521606 && lat <= 51.522606 && lon >= -0.078805 && lon <= -0.077705 ) {
console.log('you are in the area');
Session.set("locationCheck",1);
} else {
console.log('you are not in the area');
Session.set("locationCheck",0);
}
}
function error_callback(p){
return 0;
}
}
只要设置了Session.set("locationCheck",1)
(或0
),就会使用新数据重新呈现模板。
您可以在捕获位置时使用isLoading
助手:
<template name="header">
{{#if isLoading}}
Loading
{{else}}
{{#if locationCheck}}
{{>template1}}
{{else}}
{{>template0}}
{{/if}}
{{/if}}
</template>
<template name="template0">
<p>Denied</p>
</template>
<template name="template1">
Approved
</template>