维护老旧项目时发现在项目中输入框的搜索建议频繁性的显示不全,和数据接口返回的结果不一致,由于项目老旧以及交接文档不全难以维护,记录一下解决思路和过程,防止下次再遇到类似问题。
查看项目代码发现搜索建议的实现使用typeahead.js
插件,版本号为v0.11.1
插件官网:https://twitter.github.io/typeahead.js
将所有参数和方法对照文档再过一遍,没有发现任何代码问题,但是source
参数(数据来源)使用了Bloodhound
对象,由于技术水平受限没有使用过Bloodhound
插件,所以第一反应是不是Bloodhound
插件的使用上有问题。
// source参数为skuHound方法
source: skuHound,
Bloodhound
对象// 原项目代码
skuHound = new Bloodhound({
datumTokenizer : Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer : Bloodhound.tokenizers.whitespace,
remote : {
url : 'XXXXXX', // 数据接口请求路径
prepare : function(query, settings) {
settings.type = 'post',
settings.data = {
'name' : query.trim(), // 请求参数
}
return settings;
},
transform : function(parsedResponse) {
return parsedResponse.info.rows; // 返回数据
}
}
});
// 我的ajax请求
skuHound = function(query, process, asyncResults) {
$.ajax({
url: 'XXXXXX', // 数据接口请求路径
type: 'post',
dataType: 'json',
data: {
'name' : query.trim(), // 请求参数
},
success: function(result) {
var names = result.info.rows;
console.log(names)
asyncResults(names); // 返回数据
}
});
};
重启项目测试后发现并没有解决问题,控制台打印结果也正确,所以排除了是Bloodhound插件的问题。
打断点后发现typeahead.js
文件中这个方法有问题,在append元素时数量计算明显不正确。
例:最大显示数量设为20,即limit
参数设置为20
数组长度 | 插件计算的截取结束索引 | 截取后数组长度 | 结果是否正确 |
---|---|---|---|
5 | 15 | 5 | 正确,数量为5 |
16 | 4 | 4 | 不正确,应为前16 |
30 | -10 | 20 | 正确,为前20 |
改变插件中的方法:
function async(suggestions) {
suggestions = suggestions || [];
if (!canceled && rendered < that.limit) {
that.cancel = $.noop;
rendered += suggestions.length;
// that._append(query, suggestions.slice(0, that.limit - rendered)); // 原代码
that._append(query, suggestions.slice(0, that.limit)); // 改写后的代码
that.async && that.trigger("asyncReceived", query);
}
}