2016-03-04 45 views
0

我一直在試圖解決這個問題,但沒有成功。聚合物如何使用條件顯示不同的元素取決於由函數返回的布爾值?

我的代碼是:

[...] 
    <script src="lib/webcomponentsjs/webcomponents-lite.min.js"></script> 
    <link rel="import" href="lib/polymer/polymer.html"> 
    <link rel="import" href="components/app-layout.html"> 
    <link rel="import" href="components/disconnected-layout.html"> 
</head> 
<body unresolved> 
    <template> 
     <script> 
     Polymer({ 
      connected: function() { 
       var xmlHttp = new XMLHttpRequest(); 
       xmlHttp.open("GET", "127.0.0.1:5021", false); 
       xmlHttp.send(null); 
       var connection = JSON.parse(xmlHttp.responseText); 
       if (connection.success == undefined) 
       { 
        return false; 
       } 
       return !!connnection.success; 
      } 
     }); 
     </script> 
[...] 

本部分上述檢查用於連接到服務器。

在接下來的部分應該作爲選右顯示:

[...] 
     <template is="dom-if" if="{{connected()}}"> 
      <app-layout></app-layout> 
     </template> 
     <template is="dom-if" if="{{!connected()}}"> 
      <disconnected-layout></disconnected-layout> 
     </template> 
[...] 

但是,而不是連接/斷開佈局瀏覽器是顯示空白頁。 我該如何解決這個問題?

回答

0

聚合物綁定用於綁定屬性或「計算屬性」,這些屬性是在某些其他屬性發生更改時從函數動態生成的屬性。

你可以嘗試一個正常的屬性是這樣的:

Polymer({ 
    properties: { 
    connected: { 
     type: Boolean, 
     value: function() { 
     // code which returns true/false depending on whether you're connected 
     } 
    } 
    } 
}); 

當聚合物創建你的元素,它會運行一個函數來確定connected屬性的初始值,然後可以勢必喜歡你例。需要注意的是,這是一次計算,所以如果您的客戶後來脫機connected將不會更新。

的計算性質是相似的,但它們允許你到你的財產取決於元素上定義其他屬性:

Polymer({ 
    properties: { 
    otherProperty: String, 
    connected: { 
     type: Boolean, 
     computed: '_isConnected(otherProperty)' 
    } 
    }, 

    _isConnected: function(otherProperty) { 
    return otherProperty !== null; 
    } 
}) 

這將導致你的財產更新任何時候其他屬性更改。

根據您的應用,很可能是你要訂閱到瀏覽器動態地更新這個的online and offline events,在你的事件處理程序設置connectedtruefalse

看起來您具有檢測連接性的特定邏輯:尋找您的計算機上運行的服務器的響應。您可能最終需要創建一個時間間隔(setInterval)來定期檢查並相應更新屬性。

+0

感謝您的迴應,但它仍然無法正常工作。我也嘗試將值硬編碼爲true,但沒有效果。 –