dom-repeat子元素是否可以被限制为数组项



我正在尝试使用聚合物2创建一个简单的注释列表,其中每个音符在<input>元素中显示。为了创建<input>元素的列表,使用<dom-repeat>组件。我注意到,当删除数组中的项目时,<input>元素的所有value s都向上移动,并删除了最后的<input>元素。有什么方法可以删除与已删除数组项目关联的<input>元素?

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

以下是我的注释列表组件和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>

我发现这种类型的行为是在dom-repeat中实现的,但尚未合并到主分支中。可以在此处找到更多详细信息:https://github.com/polymer/polymer/issues/4558

最新更新