问题
I'm trying my hand at an autocomplete handler for Knockout.js, and I'm looking for some feedback. This currently works, but I'm trying to see if I can get the job done without so many Eval()s all over the place, and for the sake of reusability, see if there is a way to reference the ViewModel without presupposing it is named 'vm' as below.
Usage:
<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);
}
}
});
}
};
回答1:
For some inspiration, I would look at Ryan Niemeyers answer in this stackoverflow post, which is the most comprehensive autocomplete binding handler I have seen.
Another, but much simpler autocomplete binding handler which my team and I created for our own purposes can be found in this stackoverflow post
来源:https://stackoverflow.com/questions/15867569/knockout-js-autocomplete-bindinghandler