【问题标题】:Polymer two way binding聚合物双向结合
【发布时间】:2015-10-18 10:32:07
【问题描述】:

想知道如何使用聚合物双向粘合。

我有一个自制的 Polymer 元素,它通过

定义了一个布尔属性
    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>

但是当点击切换状态按钮时... 我将 log propEnabled 值切换为 true

但是页面上的togle按钮并没有改变...... 如果我添加一个简单的

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

标签也没有改变...... 对我来说,它看起来有点像一种方式绑定,它应该是 2 方式 切换按钮触发日志并正确更改组件 propEnabled 值。所以它看起来真的是一种绑定我的方式。

那么...我们如何才能真正从使用 Polymer 模板的两种方式绑定中受益????

【问题讨论】:

    标签: data-binding polymer polymer-1.0


    【解决方案1】:

    您需要通过 html 将 dom-bind 中的 propEnabled 属性分配给 test-element。

    <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

    【讨论】:

    • 好的,谢谢它的工作......如果做它也可以工作 t.set('Model.propEnabled', !t.Model.propEnabled);在按钮事件处理程序中...非常感谢!
    • @JMCourivaud。如果能解决您的问题,请考虑标记正确答案。
    猜你喜欢
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 2014-08-25
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多