2015-10-18 129 views
1

砰的一聲如何使用聚合物雙向綁定。聚合物雙向綁定

我已經聚合物元件家庭定義通過

Polymer({ 
     is: "test-element", 
     ready: function() {}, 

     properties: { 
      propEnabled: { 
       type: Boolean, 
       notify: true, 
       value: false, 
       observer: "propEnabledChanged" 
      } 
     }, 

     // Called when aoEnabled is changed 
     propEnabledChanged: function() { console.log("propEnabled value switched to " + this.propEnabled); }, 
    }); 

布爾屬性現在,我在一個HTML頁面

<body> 
    <template id="t" is="dom-bind">   
     <test-element id="testElement"></test-element> 

     <paper-toggle-button checked="{{Model.propEnabled}}">prop. enabled</paper-toggle-button> 
     <button id="switchInternalState">switch state</button>   
    </template> 
</body> 

<script> 
    var t = document.querySelector('#t'); 

    document.addEventListener('WebComponentsReady', function() { 
     console.log('WebComponentsReady'); 

     // We have to bind the template with the model 
     var t = document.querySelector('#t'); 
     t.Model = document.getElementById("testElement"); 

     // chaging the property directly does not reflect in the GUI... :-(
     var button = document.getElementById("switchInternalState"); 
     button.addEventListener("click", function() { 
      t.Model.set("propEnabled", !t.Model.propEnabled); 
     }); 
    }); 

</script> 

使用它。但是在開關狀態的按鈕點擊時。 .. 我得到的日誌propEnabled值切換爲真

但頁面上的按鈕不會改變... 如果我添加簡單

<label>{{Model.propEnabled}}</label> 

標籤也不改變... 對我來說,它看起來有點像一個雙向綁定,它應該是2的方式 切換按鈕觸發日誌,並適當地改變組件propEnabled值。所以它看起來像一種綁定到我的方式。

所以...我們如何才能真正受益於雙向綁定與聚合物模板?

回答

1

您需要通過html將dom-bind的propEnabled屬性指定給測試元素。

<test-element id="testElement" prop-enabled={{propEnabled}}></test-element> 

<paper-toggle-button checked="{{propEnabled}}">prop. enabled</paper-toggle-button> 

此外,您不需要腳本中的變量t.Model。你可以刪除它。事件監聽器應該像下面

button.addEventListener("click", function() { 
     t.propEnabled = !t.propEnabled; 
    }); 

以下plunker有工作代碼:http://embed.plnkr.co/13QJ7QFETIBg4bEiCMS7/preview

+0

它的工作原理確定感謝...它也可以,如果這樣做t.set(「Model.propEnabled」,T! .Model.propEnabled);在按鈕事件處理程序中...非常感謝! –

+0

@JMCourivaud。如果解決您的問題,請考慮標記正確的答案。 –