Meteor template helper conditional returns false consistently

半城伤御伤魂 提交于 2019-12-05 19:33:19

This is because of the callback pattern. The helpers would have already returned undefined by the time the callbacks return data. You need to use synchronous javascript inside helpers, and if having an asynchronous operation use reactive Meteor Session hashes to relay the data through:

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

Then in your header when the template is created you can fire the check off:

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;
    }
}

As soon as Session.set("locationCheck",1) (or 0) is set the template will be re-rendered with the new data.

You can use the isLoading helper while its capturing the location:

<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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!