<script src="
https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
<script src="
https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>
<script type="text/template" id="search-template">
<ul class="resultlist">
{{ if (movies.length === 0) { }}
<li class="resultlist__item">
<div class="resultlist__link">
<span class="resultlist__name h5">Ничего не найдено</span>
</div>
</li>
{{ } else { movies.slice(0, 5).forEach(function(item) { }}
<li class="resultlist__item">
<a class="resultlist__link" href="{{- item.url }}">
<span class="resultlist__title">
<span class="resultlist__name h5">{{- item.title }}</span>
{{ if (item.rating) { }}
<span class="badge badge--tiny badge--rating">
<i class="fas fa-star"></i> {{- item.rating / 10 }}
</span>
{{ } }}
</span>
<span class="resultlist__info">
{{ if (item.year) { }}
<small class="mr-auto">{{- item.genre }}</small>
{{ } }}
{{ if (item.year) { }}
<small class="ml-auto">{{- item.year }}</small>
{{ } }}
</span>
</a>
</li>
{{ }) } }}
{{ if (movies.length > 5) { }}
<li class="resultlist__item">
<a class="resultlist__link" href="{{- url}}">
<span class="resultlist__name h5">Показать все ({{- movies.length}})</span>
</a>
</li>
{{ } }}
</ul>
</script>
<script>
(function searchInit() {
var elems = document.querySelectorAll('.search-js');
_.toArray(elems).forEach(function(el) {
el.addEventListener('submit', searchHundler);
el.querySelector('input').addEventListener('input', _.debounce(function() {
var event = new Event('submit', {'cancelable': true});
this.parentNode.dispatchEvent(event);
}, 1000));
function searchHundler(event) {
event.preventDefault();
var input = this.querySelector('input'),
button = this.querySelector('button').firstElementChild;
container = this.lastElementChild;
if (input.value.length >= 3) requestResults(this, input.value, button);
else container.innerHTML = null;
function requestResults(form, query, button) {
button.classList.add('fa-spin', 'fa-spinner');
axios.get(form.action + '?json=1&q=' + query)
.then(function (response) {
response.data.url = form.action + '?q=' + query;
renderResults(response.data, form.lastElementChild);
})
.catch(function (error) {
alert('Поиск временно недоступен!');
}).then(function () {
button.classList.remove('fa-spin', 'fa-spinner');
});
}
function renderResults(data, container) {
_.templateSettings = {
evaluate: /{{([\s\S]+?)}}/g,
interpolate: /{{=([\s\S]+?)}}/g,
escape: /{{-([\s\S]+?)}}/g
};
var template = document.getElementById('search-template').innerHTML,
results = _.template(template);
container.innerHTML = results(data);
}
return false;
}
});
})();
</script>