list.js icon indicating copy to clipboard operation
list.js copied to clipboard

Template for empty values

Open DannyJoris opened this issue 4 years ago • 4 comments

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>'
};

DannyJoris avatar Jan 25 '21 20:01 DannyJoris

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>';
  },
};

DavidBruchmann avatar Jan 25 '21 23:01 DavidBruchmann

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>';
  },
};

DannyJoris avatar Jan 26 '21 00:01 DannyJoris

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.

DannyJoris avatar Feb 11 '21 16:02 DannyJoris

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')
});

kandebonfim avatar Jan 07 '22 19:01 kandebonfim