【问题标题】:Can dom-repeat child elements be bound to array items?dom-repeat 子元素可以绑定到数组项吗?
【发布时间】:2017-04-19 00:56:19
【问题描述】:

我正在尝试使用 Polymer 2 创建一个简单的笔记列表,其中每个笔记都显示在 <input> 元素中。要创建<input> 元素列表,请使用<dom-repeat> 组件。我注意到,当从数组中删除一个项目时,<input> 元素的所有 values 都向上移动,最后一个 <input> 元素被删除。有什么方法可以删除与已删除数组项关联的 <input> 元素?

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

下面是我的笔记列表组件和笔记原子组件的代码。

<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>

【问题讨论】:

  • 为什么需要从数组中删除一个项目
  • 我希望用户能够删除笔记。

标签: javascript dom polymer focus dom-repeat


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    • 2011-12-08
    • 1970-01-01
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多