简体   繁体   English

将Algolia Instantsearch.js与Autocomplete.js同步

[英]Sync Algolia Instantsearch.js with Autocomplete.js

I have set up instantsearch.js and created an index called index which looks like this: 我已经设置了Instantsearch.js并创建了一个名为index ,如下所示:

{
  "cities": [
    "Boston"
  ],
  "company": "Pineapple",
  "countries": [
    "United States",
    "Canada"
  ],
  "description": "Best pineapple in the world",
  "highlight": true,
  "productTypes": [
    "Hard Drive"
  ],
  "category": "Hardware",
  "title": "Kiwi",
  "objectID": "5"
}

I have also set up autocomplete.js and created two indices: location and country . 我还设置了autocomplete.js并创建了两个索引: locationcountry

This is location : 这是location

{
  "cities": "San Francisco",
  "objectID": "91961120"
}

This is country : 这是country

{
  "countries": "Germany",
  "objectID": "92132590"
}

I have gotten both functions to work separately, but I do not know how to sync them. 我已经将这两个功能分开工作,但是我不知道如何同步它们。

The behavior I'm looking for is that a user can input a search with the help of instantsearch.js and use autocomplete.js to select a location or country to filter down the results. 我正在寻找的行为是用户可以在Instantsearch.js的帮助下输入搜索,并使用autocomplete.js选择位置或国家/地区来过滤结果。 Alternatively, the user can just use autocomplete.js to filter the results by country/location. 或者,用户可以只使用autocomplete.js来按国家/地区过滤结果。

I've created a Codepen to show my code. 我创建了一个Codepen来显示我的代码。 Thanks. 谢谢。

I know the naming conventions I'm using are not the best, these will be changed. 我知道我使用的命名约定不是最好的约定,这些约定将被更改。

You need to make sure that cities and countries are declared as attributesForFaceting in your main index. 您需要确保在主索引中将citiescountries声明为attributesForFaceting Then you will need to add the attribute facets on the initial searchParameters of instantsearch . 然后,你将需要添加的属性facets的初始searchParametersinstantsearch This attribute will contain the name of the facets that you want to use ( cities & countries ). 该属性将包含您要使用的构面的名称( citiescountries )。 From now should be able to apply facet filters on your attributes. 从现在开始,应该可以在属性上应用构面过滤器。

In order to sync both instance you need to listen the autocomplete:selected event. 为了同步两个实例,您需要侦听autocomplete:selected事件。 You will also probably need to listen for the change event on the input and clear the filters when there is no value. 您可能还需要侦听输入上的change事件,并在没有值时清除过滤器。 For applying the filters you will need to use the helper , it's the internal library used by instantsearch for managing the state. 为了应用过滤器,您将需要使用helper ,这是instantsearch用于管理状态的内部库。

I updated your Codepen with the changes explain above. 我使用上述更改更新了Codepen

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM