在Polymer中,双向绑定与属性表达式是否可能

Is two way binding with an attribute expression possible in Polymer?

本文关键字:表达式 属性 是否 绑定 Polymer      更新时间:2024-01-29

我注意到,双向绑定只有在表达式为时才有效变量名本身(例如{{value}})。如果表达式需要对值(例如{{value*5}})进行操作,则双向绑定将中断。这是Polymer中的一个限制吗?对于需要从表达式中导出的许多值的用例,有什么变通方法吗?

  Clicking the +/- buttons should increment all 3 numbers at the same time.
  <br/>
  <br/>
   <polymer-element name='test-input'>
       <template>
           <style>
               #val {
                   font-size: 50px;
               }
           </style>
           <div id='val'>{{value}}</div>
           <button on-tap='{{increment}}'>+</button>
           <button on-tap='{{decrement}}'>-</button>
       </template>
       <script>
           Polymer({
               publish: {
                   value: 0
               },
               increment: function() {
                   this.value = this.value + 1;
               },
               decrement: function() {
                   this.value = this.value - 1;
               }
           })
       </script>
   </polymer-element>
   <polymer-element name='test-app'>
       <template>
           Hue:
           <b>{{hue}}</b>
           <br/>
           <br/>
           First:
           <test-input id='two' value='{{hue}}'></test-input>
           <br/>
           (this one works)
           <br/>
           <br/>
           Second:
           <test-input id='one' value='{{hue * 5}}'></test-input>
           <br/>
           (this one does not work)

       </template>
       <script>
           Polymer({ 
               hue: 5,
           })
       </script>
   </polymer-element>

   <test-app></test-app>

http://plnkr.co/edit/KjQ9DusaFg2jp1BTFUde?p=preview

谢谢你的帮助。

Plunk中出现的下一个错误意味着元素导入顺序错误:

"测试输入的属性在聚合物升级元素之前进行了数据绑定。这可能导致不正确的绑定类型。"

只需切换元素定义的顺序。

这是更正后的Plunk。

<body>

           <polymer-element name='test-input' attributes="testData">
           ...

编辑:

这里有一个解决这个问题的方法。问题出现在子元素属性中使用表达式时:

//1. this is not working
<test-input id='one' value='{{hue * 10}}'></test-input>
//2. this works
<test-input id='one' value='{{hue}}'></test-input>
//3. multiplying is done in the child element using filter:
{{value | myltiply}}

这是正在工作的Plunk

不知道为什么1。不起作用,我也想知道它的背景。

以下是一个简单的演示,说明当绑定输入值属性内时,Polymer为什么不更新属性。

<polymer-element name='my-test-element'>
    <template>
        Number: {{num}}<br>
        <input id='one' value='{{num}}' on-keypress='{{keyPressHandler}}' /><br>
        Value: {{$.one.value}}
    </template>
    <script>
        Polymer({
            num: 0,
            keyPressHandler: function(){
                this.$.one.value = this.num*4;
            }
        });
    </script>
</polymer-element>

这也会产生同样的效果。每次更改值时,输入中的值都会发生变化。情况不言自明。。。

编辑:Plunk:http://plnkr.co/edit/UEoqBGXAyzROJsP20suU?p=preview