2013-05-14 78 views
4

我對流星很新,但到目前爲止,我真的很喜歡在平臺上編碼。我遇到了一些障礙,似乎找不到正確的方法。我想創建一個幫助函數,它將檢查經緯度和長度,並檢查它是否在某些預定義範圍內,如果它落在這些範圍之間,它將返回true。流星模板助手條件一致返回false

我已經包含的代碼我目前有:

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

的問題是即使在控制檯它返回這個you are in the area,它仍然一致地返回else語句結果。

任何幫助都會很棒。

在此先感謝。

回答

3

這是因爲回調模式。在回調函數返回數據時,助手已經返回undefined。您需要使用內部助手同步JavaScript中,如果有一個異步操作使用reactive流星Sessionhashes通過中繼數據:在你的頭

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> 
+0

,這似乎是偉大的工作,只是爲了澄清是否有可能傳遞參數,以便設置之前,我可以呈現裝載模板? – 2013-05-14 10:52:45

+0

我添加了另一個'isLoading'幫手,你可以使用它來顯示一條消息,同時它獲得座標 – Akshat 2013-05-14 12:56:39

+0

啊,似乎已經做到了這一點。如果你看看'getCurrentPosition'函數,你會看到有2個結果成功和失敗,我如何返回一個不同的模板,取決於它是否被接受或拒絕。 – 2013-05-14 13:17:13