dom-repeat子元素可以绑定到数组项吗?

时间:2017-04-19 00:56:20

标签: javascript dom polymer focus dom-repeat

我正在尝试使用Polymer 2创建一个简单的音符列表,其中每个音符都显示在<input>元素中。要创建<input>元素列表,请使用<dom-repeat>组件。我注意到,当删除数组中的某个项时,value元素的所有<input>都会向上移动,并删除最后一个<input>元素。有没有办法删除与已删除的数组项关联的<input>元素?

我意识到这通常不会是一个严重的问题,但是使用<input>元素时,焦点将绑定到实际的DOM对象。为了使焦点正确,删除备注时value元素的<input>属性不应更改。

下面是我的笔记列表组件和note-atom组件的代码。

<dom-module id="note-list">
<template>
    <ul>
    <template is="dom-repeat" items="{{notes}}">
        <li>
        <note-atom
            on-delete="_onNoteDelete"
            on-blur="_onNoteBlur"
            value="{{item.note}}">
        </note-atom>
        </li>
    </template>
    <li>
        <note-atom value={{_newNote}}></note-atom>
    </li>
    </ul>
</template>

<script>
    class NoteList extends Polymer.Element {
    static get is() { return 'note-list'; }
    static get properties() {
        return {
        notes: {
            type: Array,
            value: [],
            notify: true
        },
        _newNote: {
            type: String,
            value: '',
            observer: "_newNoteChanged"
        }
        };
    }

    _newNoteChanged(newValue, oldValue) {
        if (newValue !== '') {
        this._newNote = '';
        this.push('notes', {"note": newValue});
        }
    }

    _onNoteDelete(e) {
        const noteIdx = this.notes.indexOf(e.model.item);
        this.splice('notes', noteIdx, 1);
    }

    _onNoteBlur(e) {
        if (e.model.item.note === '') {
        this._onNoteDelete(e);
        }
    }

    }

    window.customElements.define(NoteList.is, NoteList);
</script>
</dom-module>


<dom-module id="note-atom">
<template>
    <input type='text'
    value="{{value::change}}"
    on-blur="_onInputBlur"
    placeholder='A new note...' />
    <button on-click="_onDeleteButton">X</button>
</template>

<script>
    class NoteAtom extends Polymer.Element {
    static get is() { return 'note-atom'; }
    static get properties() {
        return {
        value: {
            type: String,
            value: '',
            notify: true
        }
        };
    }

    _onDeleteButton() {
        this.dispatchEvent(new CustomEvent('delete'));
    }

    _onInputBlur() {
        this.dispatchEvent(new CustomEvent('blur'));
    }
    }

    window.customElements.define(NoteAtom.is, NoteAtom);
</script>
</dom-module>

1 个答案:

答案 0 :(得分:0)

我发现这种行为是在dom-repeat中实现的,但还没有合并到master分支中。更多细节可以在这里找到:https://github.com/Polymer/polymer/issues/4558