meteor模板助手条件一贯返回false

我对meteor很新,但到目前为止,我真的很喜欢这个平台的编码。 我碰到了一些障碍,似乎找不到正确的方法。 我想创build一个帮助函数,将检查经纬度和检查它对预定义的范围,如果它落在这些之间它返回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 locationCheck}} {{loginButtons}} {{else}} <p>Your are out of the vicinity</p> {{/if}} 

问题是一直返回else语句的结果,即使在控制台中它正在返回you are in the area

任何帮助都是极好的。

提前致谢。

这是因为callback模式。 在callback函数返回数据的时候,helpers已经返回undefined。 您需要在助手中使用同步JavaScript,如果有asynchronous操作,则使用响应式meteorSession 哈希来通过以下方式中继数据:

 Template.header.helpers({ locationCheck: function() { return Session.get("locationCheck"); }, isLoading:function() { return Session.equals("locationCheck",null); } }); 

然后在模板创build的时候,在你的头文件中,你可以启动这个检查:

 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>