在Polymer中可以使用属性表达式双向绑定吗?

时间:2015-02-19 11:54:36

标签: javascript html polymer

我注意到双向绑定仅在表达式变量名称本身时才起作用(例如,{{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

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

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

&#34;测试输入的属性是在Polymer升级元素之前绑定的数据。这可能会导致绑定类型不正确。&#34;

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

以下是更正的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.不起作用,我也想知道它的背景。

答案 1 :(得分:0)

这是一个简单的演示,说明当输入值属性中的绑定时,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