list.js
list.js copied to clipboard
Template for empty values
Is there a way to render an "empty" message when an empty array is passed to the List object? It would be handy to be able to add a template like you do for items whenever there are no values passed.
For example with an empty template:
const options = {
item: function(values) {
return `<li>${values.name}"></li>`;
},
empty: '<li>No results</li>'
};
You might have to correct in detail but I guess you understand the approach:
const options = {
item: function(values) {
return values.length ? `<li>${values.name}"></li>` : '<li>No results</li>';
},
};
Yeah that's where I landed as well. Though the item function doesn't get called when there's no values. Also values is an object so length doesn't work. So I made a workaround by prepping the data like this instead:
const values = data.length ?
data.map(el => ({
name: el.name
})) : {
empty: true
};
and then:
const options = {
item: function(values) {
return !values.empty ? `<li>${values.name}"></li>` : '<li>No results</li>';
},
};
A solution if you use existing HTML instead of item templates + search is to add it in the update event. If you use the search filter and it doesn't match anything you can do:
let myList = new List('my-list', options)
.on('updated', function(list) {
if (list.matchingItems.length == 0) {
$('.my-list').append('<tr><td colspan="2">No items found</td></tr>');
}
});
You manually add a row when no results are found. When you remove the search filter query, the values will override the placeholder you just put in there.
It would still be handy to be able to set this as a property in the options object to account for all these scenarios.
Inspired by @DannyJoris, I went with
var hackerList = new List('my-list', options).on('updated', function(list) {
$('.list__empty')[list.matchingItems.length == 0 ? "addClass" : "removeClass"]('visible')
});