#javascript #input #salesforce #debounce #lwc
Вопрос:
При вводе пользователь пишет поисковую фразу для поиска товаров. И я хотел бы установить поиск после того, как пользователь перестал печатать. Вот хороший пример, но он не работает в веб-компонентах Lightning. Когда я начинаю писать в поисковый ввод, появляется ошибка: «На этой странице ошибка. Возможно, вам просто нужно его обновить.»
productList.html:
<lightning-input
type="search"
class="slds-var-m-bottom_small"
value={searchKey}
placeholder="Searching..."
onchange={handleSearchEvent}>
</lightning-input>
productList.js:
import { LightningElement, wire } from 'lwc';
import findProducts from '@salesforce/apex/ProductMaster.findProducts';
export default class ProductList extends LightningElement {
searchKey = '';
timeout = null;
@wire(findProducts, { searchKey: '$searchKey' })
products;
handleSearchEvent(event) {
const eventValue = event.target.value;
clearTimeout(timeout);
timeout = setTimeout(function (eventValue) {
this.searchKey = eventValue;
console.clear();
console.log('handleSearchEvent() -> this.searchKey: ' this.searchKey);
}, 1000); // searching after 1s
}
}
Как нужно установить тайм-аут?
И консоль js пишет:
console.log('handleSearchEvent() -> this.searchKey: ' this.searchKey);
handleSearchEvent() -> this.searchKey: undefined
Ответ №1:
Проблема в том, что ваша this
привязка в вашей функции должна быть явно задана:
timeout = setTimeout(function (eventValue) {
this.searchKey = eventValue;
console.clear();
console.log('handleSearchEvent() -> this.searchKey: ' this.searchKey);
}.bind(this), 1000);
Но, возможно, более простым способом было бы просто использовать функцию со стрелкой, которая this
, я полагаю, будет неявно связывать:
timeout = setTimeout((eventValue) => {
this.searchKey = eventValue;
console.clear();
console.log('handleSearchEvent() -> this.searchKey: ' this.searchKey);
}, 1000);