Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   Debounce input выдает ошибку (https://javascript.ru/forum/dom-window/80494-debounce-input-vydaet-oshibku.html)

ab3 12.06.2020 14:06

Debounce input выдает ошибку
 
Хочу затормозить ввода интпута для поиска,использую lodash.debounce,debounce работает(консоль выводит),но когда доходит до инпута выдает ошибку:
country.js?dc0a:18 Uncaught TypeError: Cannot read property 'elements' of null
at HTMLFormElement.searchInputHandler (country.js?dc0a:18)
at invokeFunc (index.js?8df7:160)
at trailingEdge (index.js?8df7:207)
at timerExpired (index.js?8df7:195)


Если не использовать debounce то все работает отлично,подскажите в чем проблема?Почему пишет null не могу понять:(

Вот мой код:
import countryListItem from '../templates/counry-list-item.hbs';
import countryList from '../templates/country-list.hbs';
import fetchCountry from '../services/fetch-country.js';
import debounce from 'lodash.debounce';
import { Notyf } from 'notyf';

const notyf = new Notyf();

const refs = {
  counryList: document.querySelector('#country-list'),
  seacrhForm: document.querySelector('#search-form'),
};

// refs.seacrhForm.addEventListener('input', debounce(searchInputHandler, 500));
refs.seacrhForm.addEventListener('input', searchInputHandler);

function searchInputHandler(e) {
  clearListItem();

  console.log('aaa');

  const form = e.currentTarget;
  const input = form.elements.query;
  const inputValue = input.value;

  if (inputValue === '') {
    return;
  } else {
    fetchCountry.query = inputValue;

    fetchCountry
      .fetchCountries()
      .then(data => {
        if (data.length > 10) {
          notyf.error(
            'Too many matches found.Please enter a more specific query!',
          );
        } else if (data.length >= 2 && data.length <= 10) {
          renderCountryList(data);
        } else if (data.length === 1) {
          renderCountryListItems(data);
        } else notyf.error('Nothing found.Please enter a valid request');
      })
      .catch(error => console.log(error));
  }
}

function renderCountryListItems(items) {
  const markup = items.map(item => countryListItem(item)).join('');
  buildCountryList(markup);
}

function renderCountryList(items) {
  const markup = countryList(items);
  buildCountryList(markup);
}

function buildCountryList(item) {
  refs.counryList.insertAdjacentHTML('beforeend', item);
}

function clearListItem() {
  refs.counryList.innerHTML = '';
}

рони 12.06.2020 14:40

ab3,
const form = document.querySelector('form');

Пожалуйста, отформатируйте свой код!

Для этого его можно заключить в специальные теги: js/css/html и т.п., например:
[html run]
... минимальный код страницы с вашей проблемой
[/html]

О том, как вставить в сообщение исполняемый javascript и html-код, а также о дополнительных возможностях форматирования - читайте http://javascript.ru/formatting.

ab3 12.06.2020 15:23

Переделал,я подключался к форме,просто скидывал не весь код(не смог найти как правильно выкладывать код на форум и поэтому скинул только малую часть)без debounce все работает с debounce только

clearListItem();

  console.log('aaa');

  const form = e.currentTarget;

рони 12.06.2020 15:44

ab3,
вы меняли строку 22
const form = e.currentTarget;

на
const form = document.querySelector('form');

?

ab3 12.06.2020 15:52

Спасибо,так работает,но я так обращаюсь на прямую к форме и если у меня 2 формы,то работать не будет,вернее будет находить первую...Нашел ошибку,нужно было обращаться e.target.value.Чет сразу не додумался проконсолить event:)

рони 12.06.2020 16:46

ab3,
const form = e.path.find(({localName})=> localName == 'form');


Часовой пояс GMT +3, время: 03:22.