我正在尝试使用 Knockout.js 的自动完成处理程序,并且正在寻找一些反馈。这目前有效,但我想看看我是否可以在没有那么多 Eval() 的情况下完成工作,并且为了可重用性,看看是否有一种方法可以在不预设的情况下引用 ViewModel被命名为“vm”,如下所示。
用法:
<input placeholder="Test..." type="search" data-bind="autoComplete:$root.persons, source:'/api/Person/', parameterName:'searchString', labelKey:'displayName', valueKey:'urid', onSelected:'addPerson'" autocomplete="off" />
JS:
ko.bindingHandlers.autoComplete = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var postUrl = allBindingsAccessor().source; // url to post to is read here
var param = allBindingsAccessor().parameterName;
var labelKeyName = allBindingsAccessor().labelKey;
var valueKeyName = allBindingsAccessor().valueKey;
var selectedFunction = allBindingsAccessor().onSelected;
var selectedObservableArrayInViewModel = valueAccessor();
$(element).autocomplete({
minLength: 2,
autoFocus: true,
source: function (request, response) {
$.ajax({
url: param != null ? postUrl : postUrl + request.term,
data: param == null ? '' : param + "=" + request.term,
dataType: "json",
type: "GET",
success: function (data) {
response($.map
(data, function (obj) {
return {
label: eval("obj." + labelKeyName),
value: eval("obj." + valueKeyName)
};
}));
}
});
},
select: function (event, ui) {
if (selectedFunction != null) {
var functionCall = 'vm.' + selectedFunction + "(event, ui)";
eval(functionCall);
}
}
});
}
};