From 10432a79dfb1582ba2c324608e5629d82edfd6e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pekka=20Maanp=C3=A4=C3=A4?= Date: Thu, 16 May 2019 14:32:04 +0300 Subject: [PATCH] fix: allow changing value in value-changed listener fix #651 The else-if added at line 886 prevents duplicate events. --- src/vaadin-combo-box-mixin.html | 9 +++++--- test/selecting-items.html | 38 +++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/src/vaadin-combo-box-mixin.html b/src/vaadin-combo-box-mixin.html index 149d606fe..45131baf0 100644 --- a/src/vaadin-combo-box-mixin.html +++ b/src/vaadin-combo-box-mixin.html @@ -707,6 +707,11 @@ const value = this._getItemValue(selectedItem); if (this.value !== value) { this.value = value; + if (this.value !== value) { + // The value was changed to something else in value-changed listener, + // so prevent from resetting it to the previous value. + return; + } } this._updateHasValue(true); @@ -878,9 +883,7 @@ if (this.opened) { this._focusedIndex = this.filteredItems.indexOf(e.detail.item); this.close(); - } - - if (this.selectedItem !== e.detail.item) { + } else if (this.selectedItem !== e.detail.item) { this.selectedItem = e.detail.item; this._detectAndDispatchChange(); } diff --git a/test/selecting-items.html b/test/selecting-items.html index 4d6da2da4..8a7e14a39 100644 --- a/test/selecting-items.html +++ b/test/selecting-items.html @@ -174,6 +174,44 @@ expect(newComboBox.value).to.equal('foo'); }); + it('should allow changing the value in value-changed listener', done => { + combobox.open(); + const items = combobox.$.overlay._selector.querySelectorAll('vaadin-combo-box-item'); + + combobox.addEventListener('value-changed', () => { + if (combobox.value === 'foo') { + combobox.value = 'bar'; + setTimeout(() => { + expect(combobox.value).to.eql('bar'); + expect(combobox.selectedItem).to.eql('bar'); + expect(items[0].selected).to.be.false; + expect(items[1].selected).to.be.true; + done(); + }); + } + }); + items[0].click(); + }); + + it('should allow clearing the value in value-changed listener', done => { + combobox.open(); + const item = combobox.$.overlay._selector.querySelector('vaadin-combo-box-item'); + + combobox.addEventListener('value-changed', () => { + if (combobox.value) { + combobox.value = ''; + setTimeout(() => { + expect(combobox.value).to.eql(''); + expect(combobox.selectedItem).not.to.be.ok; + expect(item.selected).to.be.false; + expect(combobox.hasAttribute('has-value')).to.be.false; + done(); + }); + } + }); + item.click(); + }); + describe('`change` event', () => { it('should fire `value-changed` and `selected-item-changed` before `changed`', done => { combobox.addEventListener('change', () => {