如果没有返回命中,则为Algolia模板

PER*_*RPO 1 javascript algolia

我已经实现了我自己的基于https://www.algolia.com/doc/search/auto-complete的Algolia PoC ,我现在正在努力解决一个特定的用例:如何处理一个不返回任何用户的搜索点击?

这是我的代码:

我已经能够识别并检测何时/何地没有返回命中,但除了使用console.log()之外我无法做任何事情.我试图获得自定义的return_msg,但我无法调用该函数.我还尝试在建议下做一些调整:函数(建议)但是如果没有返回命中,则永远不会调用此函数.我也没有在https://github.com/algolia/autocomplete.js上找到关于这个"模板"部分的任何文档.

$('#q').autocomplete({ hint: false }, [
    {
      source: function(q, cb) {
        index.search(q, 
          { hitsPerPage: 10 }, 
          function(error, content) {
                  if (error) {
                    cb([]);
                    return;
                  }

                  if (content.nbHits == 0)
                    { return_msg = '<h5> Sorry, no result </h5>';
                      // DO something here
                      console.log(return_msg);
                     // console.log return "Sorry, no result"
                     }

                  cb(content.hits, content);

                });
          },
      displayKey: 'game',
      templates: {
        suggestion: function(suggestion) {
          return_msg = '<h5> '+ suggestion.MY_ATTRIBUTE + '</h5>'
        return return_msg;
        }
      }
    }
  ]).on('autocomplete:selected', function(event, suggestion, dataset) {
     window.location = (suggestion.url);
  });
Run Code Online (Sandbox Code Playgroud)

任何指针将不胜感激=)

red*_*dox 6

使用templates数据集选项,您可以指定在没有结果时使用的模板:

source: autocomplete.sources.hits(indexObj, { hitsPerPage: 2 }),
templates: {
  suggestion: // ...
  header:  // ...
  footer:  // ...
  empty: function(options) {
    return '<div>My empty message</div>';
  }
}
Run Code Online (Sandbox Code Playgroud)

完整文档在这里.