【发布时间】:2017-04-26 13:23:37
【问题描述】:
我正在尝试使用 Typeahead/Bloodhound 进行建议和搜索。为简单起见,假设我有两种类型的模型对象 - Country 和 City。
public class Country
{
public string Name { get; set; }
}
(服务器端在 ASP.NET 中,但这与问题无关)。
City 与 Country 几乎相同,只是名称不同。
无论如何,在造型之前,我希望最终结果如下所示:
(如果不明显,我在文本框中写了“AL”,其余字母构成第一个建议)
我可以通过使用多个 Bloodhounds 轻松实现这一点:
var countries = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 5,
remote: {
url: 'http://localhost:5000/api/countries/%QUERY',
wildcard: '%QUERY'
}
});
var cities = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 5,
remote: {
url: 'http://localhost:5000/api/cities/%QUERY',
wildcard: '%QUERY'
}
});
和多个输入对象提前输入:
$('#remote .typeahead').typeahead(null,
{
name: 'countries',
display: 'name',
source: countries,
templates: {
empty: [
'<div class="empty-message">',
'unable to find any countries that match the current query',
'</div>'
].join('\n'),
suggestion: Handlebars.compile('<div><strong>{{name}}</strong></div>'),
header: '<h2>Countries</h2>'
}
},
{
name: 'cities',
display: 'name',
source: cities,
templates: {
empty: [
'<div class="empty-message">',
'unable to find any cities that match the current query',
'</div>'
].join('\n'),
suggestion: Handlebars.compile('<div><strong>{{name}}</strong></div>'),
header: '<h2>Cities</h2>'
}
});
但是,在我的真实场景中,我有大约 10 个数据集。创建 10 个单独的查询,结合 JSON 序列化/反序列化可能会当场杀死我的服务器,尤其是在有多个用户的情况下。
我更喜欢有一个复合 DTO:
public class CompositeSearchResult
{
public List<Country> Countries { get; set; }
public List<City> Cities { get; set; }
//... and many others
}
...同时使用 Bloodhound 以某种方式处理客户端上的复杂对象。这可能吗?
【问题讨论】:
标签: javascript json typeahead.js bloodhound