聚合物从模板dom-repeat

时间:2017-06-01 08:47:07

标签: polymer onchange dom-repeat

为了从输入中获取更改,我使用以下

    <template is="dom-repeat" items="{{employees}}">
    <div>First name: <input on-change="cambiado" value="{{item.first::change}}"></div>
    <div>Last name: <input on-change="cambiado" value="{{item.last::change}}"></div>
    </template> 
...
<script>
...
cambiado(e){
    var datos=this.employees[e.model.__data.index]
    setTimeout(function() {
        console.log(datos.first+'  '+datos.last)
    }, 1000);
}
...

</script> 

但我确信Polymer可以更轻松地获取事件或只是改变输入。感谢。

这个观察者的完整元素不起作用:

   <link rel="import" href="../bower_components/polymer/polymer.html">

<dom-module id='employee-list'>
    <template>
        <div>Employee List</div>
        <p></p>
        <template is="dom-repeat" items="{{employees}}">
            <div>First name: <input value="{{item.first}}"></div>
            <div>Last name: <input value="{{item.last}}"></div>
        </template>
    </template>

    <script>
        class EmployeeList extends Polymer.Element {
            static get is() { return 'employee-list' }
            static get properties() {
                return {
                    item: {
                        type: Object,
                        value: function () {
                            return {};
                        }
                    }
                }
            }
            static get observers() {
                return [
                    'itemChanged(item.*)'
                ]
            }
            constructor() {
                super()
                this.employees = [
                    { first: 'Bob', last: 'Li' },
                    { first: 'Ayesha', last: 'Johnson' },
                    { first: 'Fatma', last: 'Kumari' },
                    { first: 'Tony', last: 'Morelli' }
                ];
            }

            itemChanged(first) {
                if (first) {
                    console.log('new first: ' + first);
                } else {
                    console.log('first is undefined');
                }
            }
        }
        customElements.define(EmployeeList.is, EmployeeList)
    </script>
</dom-module>

1 个答案:

答案 0 :(得分:2)

你可以使用observer,所以当item对象的某些属性被更改时,会调用名为function的函数:

observers: [
  'itemChanged(item.*, cambiado)'
]

文档:https://www.polymer-project.org/1.0/docs/devguide/observers