Javascript 如何创建自动完成组合框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7537002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create an auto-complete combobox?
提问by Craig Bruce
Does any one know the best way to create an autocomplete combobox with Knockout JS templates?
有人知道使用 Knockout JS 模板创建自动完成组合框的最佳方法吗?
I have the following template:
我有以下模板:
<script type="text/html" id="row-template">
<tr>
...
<td>
<select class="list" data-bind="options: SomeViewModelArray,
value: SelectedItem">
</select>
</td>
...
<tr>
</script>
Sometimes this list is long and I'd like to have Knockout play nicely with perhaps jQuery autocomplete or some straight JavaScript code, but have had little success.
有时这个列表很长,我希望 Knockout 可以很好地与 jQuery 自动完成或一些直接的 JavaScript 代码一起使用,但收效甚微。
In addition, jQuery.Autocomplete requires an input field. Any ideas?
此外,jQuery.Autocomplete 需要一个输入字段。有任何想法吗?
回答by RP Niemeyer
Here is a jQuery UI Autocomplete binding that I wrote. It is intended to mirror the options
, optionsText
, optionsValue
, value
binding paradigm used with select elements with a couple of additions (you can query for options via AJAX and you can differentiate what is displayed in the input box vs. what is displayed in the selection box that pops up.
这是我编写的 jQuery UI 自动完成绑定。它旨在通过一些添加来反映与 select 元素一起使用的options
, optionsText
, optionsValue
,value
绑定范式(您可以通过 AJAX 查询选项,您可以区分输入框中显示的内容与弹出的选择框中显示的内容向上。
You do not need to provide all of the options. It will choose defaults for you.
您不需要提供所有选项。它将为您选择默认值。
Here is a sample without the AJAX functionality: http://jsfiddle.net/rniemeyer/YNCTY/
这是一个没有 AJAX 功能的示例:http: //jsfiddle.net/rniemeyer/YNCTY/
Here is the same sample with a button that makes it behave more like a combo box: http://jsfiddle.net/rniemeyer/PPsRC/
这是带有按钮的相同示例,使其更像一个组合框:http: //jsfiddle.net/rniemeyer/PPsRC/
Here is a sample with the options retrieved via AJAX: http://jsfiddle.net/rniemeyer/MJQ6g/
以下是通过 AJAX 检索选项的示例:http: //jsfiddle.net/rniemeyer/MJQ6g/
//jqAuto -- main binding (should contain additional options to pass to autocomplete)
//jqAutoSource -- the array to populate with choices (needs to be an observableArray)
//jqAutoQuery -- function to return choices (if you need to return via AJAX)
//jqAutoValue -- where to write the selected value
//jqAutoSourceLabel -- the property that should be displayed in the possible choices
//jqAutoSourceInputValue -- the property that should be displayed in the input box
//jqAutoSourceValue -- the property to use for the value
ko.bindingHandlers.jqAuto = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
var options = valueAccessor() || {},
allBindings = allBindingsAccessor(),
unwrap = ko.utils.unwrapObservable,
modelValue = allBindings.jqAutoValue,
source = allBindings.jqAutoSource,
query = allBindings.jqAutoQuery,
valueProp = allBindings.jqAutoSourceValue,
inputValueProp = allBindings.jqAutoSourceInputValue || valueProp,
labelProp = allBindings.jqAutoSourceLabel || inputValueProp;
//function that is shared by both select and change event handlers
function writeValueToModel(valueToWrite) {
if (ko.isWriteableObservable(modelValue)) {
modelValue(valueToWrite );
} else { //write to non-observable
if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers']['jqAutoValue'])
allBindings['_ko_property_writers']['jqAutoValue'](valueToWrite );
}
}
//on a selection write the proper value to the model
options.select = function(event, ui) {
writeValueToModel(ui.item ? ui.item.actualValue : null);
};
//on a change, make sure that it is a valid value or clear out the model value
options.change = function(event, ui) {
var currentValue = $(element).val();
var matchingItem = ko.utils.arrayFirst(unwrap(source), function(item) {
return unwrap(item[inputValueProp]) === currentValue;
});
if (!matchingItem) {
writeValueToModel(null);
}
}
//hold the autocomplete current response
var currentResponse = null;
//handle the choices being updated in a DO, to decouple value updates from source (options) updates
var mappedSource = ko.dependentObservable({
read: function() {
mapped = ko.utils.arrayMap(unwrap(source), function(item) {
var result = {};
result.label = labelProp ? unwrap(item[labelProp]) : unwrap(item).toString(); //show in pop-up choices
result.value = inputValueProp ? unwrap(item[inputValueProp]) : unwrap(item).toString(); //show in input box
result.actualValue = valueProp ? unwrap(item[valueProp]) : item; //store in model
return result;
});
return mapped;
},
write: function(newValue) {
source(newValue); //update the source observableArray, so our mapped value (above) is correct
if (currentResponse) {
currentResponse(mappedSource());
}
}
});
if (query) {
options.source = function(request, response) {
currentResponse = response;
query.call(this, request.term, mappedSource);
}
} else {
//whenever the items that make up the source are updated, make sure that autocomplete knows it
mappedSource.subscribe(function(newValue) {
$(element).autocomplete("option", "source", newValue);
});
options.source = mappedSource();
}
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).autocomplete("destroy");
});
//initialize autocomplete
$(element).autocomplete(options);
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
//update value based on a model change
var allBindings = allBindingsAccessor(),
unwrap = ko.utils.unwrapObservable,
modelValue = unwrap(allBindings.jqAutoValue) || '',
valueProp = allBindings.jqAutoSourceValue,
inputValueProp = allBindings.jqAutoSourceInputValue || valueProp;
//if we are writing a different property to the input than we are writing to the model, then locate the object
if (valueProp && inputValueProp !== valueProp) {
var source = unwrap(allBindings.jqAutoSource) || [];
var modelValue = ko.utils.arrayFirst(source, function(item) {
return unwrap(item[valueProp]) === modelValue;
}) || {};
}
//update the element with the value that should be shown in the input
$(element).val(modelValue && inputValueProp !== valueProp ? unwrap(modelValue[inputValueProp]) : modelValue.toString());
}
};
You would use it like:
你会像这样使用它:
<input data-bind="jqAuto: { autoFocus: true }, jqAutoSource: myPeople, jqAutoValue: mySelectedGuid, jqAutoSourceLabel: 'displayName', jqAutoSourceInputValue: 'name', jqAutoSourceValue: 'guid'" />
UPDATE: I am maintaining a version of this binding here: https://github.com/rniemeyer/knockout-jqAutocomplete
更新:我在这里维护这个绑定的一个版本:https: //github.com/rniemeyer/knockout-jqAutocomplete
回答by Epstone
Here is my solution:
这是我的解决方案:
ko.bindingHandlers.ko_autocomplete = {
init: function (element, params) {
$(element).autocomplete(params());
},
update: function (element, params) {
$(element).autocomplete("option", "source", params().source);
}
};
Usage:
用法:
<input type="text" id="name-search" data-bind="value: langName,
ko_autocomplete: { source: getLangs(), select: addLang }"/>
http://jsfiddle.net/7bRVH/214/Compared to RP's it is very basic but maybe fills your needs.
http://jsfiddle.net/7bRVH/214/与 RP 相比,它是非常基本的,但也许可以满足您的需求。
回答by George Mavritsakis
Disposal needed....
需要处理....
Both of those solutions are great (with Niemeyer's being much more fine grained) but they both forget the disposal handling!
这两种解决方案都很棒(尼迈耶的粒度更细),但它们都忘记了处置处理!
They should handle disposals by destroying jquery autocomplete (prevent memory leakages) with this:
他们应该通过销毁 jquery 自动完成(防止内存泄漏)来处理处置:
init: function (element, valueAccessor, allBindingsAccessor) {
....
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).autocomplete("destroy");
});
}
回答by Antonio Inacio
Minor improvements,
小改进,
First of all these are some very useful tips, thank you all for sharing.
首先这些是一些非常有用的技巧,谢谢大家的分享。
I'm using the version posted by Epstonewith the following improvements:
我正在使用Epstone发布的版本,并进行了以下改进:
Display the label (instead of the value) when pressing up or down - apparently this can be done by handling the focus event
Using an observable array as the data source (instead of an array)
- Added the disposable handler as suggested by George
向上或向下按时显示标签(而不是值) - 显然这可以通过处理焦点事件来完成
使用 observable 数组作为数据源(而不是数组)
- 按照George 的建议添加了一次性处理程序
...
conf.focus = function (event, ui) {
$(element).val(ui.item.label);
return false;
}
...
Btw, specifying minLengthas 0 allows displaying the alternatives by just moving the arrow keys without having to enter any text.
顺便说一句,将minLength指定为 0 允许仅通过移动箭头键而无需输入任何文本来显示备选方案。
回答by chomba
I tried Niemeyer's solutionwith JQuery UI 1.10.x, but the autocomplete box simply didn't show up, after some searching i found a simple workaround here. Adding the following rule to the end of your jquery-ui.css file fixes the problem:
我在 JQuery UI 1.10.x 上尝试了Niemeyer 的解决方案,但自动完成框根本没有出现,经过一番搜索后,我在这里找到了一个简单的解决方法。将以下规则添加到 jquery-ui.css 文件的末尾可以解决问题:
ul.ui-autocomplete.ui-menu {
z-index: 1000;
}
I also used Knockout-3.1.0, so I had to replace ko.dependentObservable(...) with ko.computed(...)
我还使用了 Knockout-3.1.0,所以我不得不用 ko.computed(...) 替换 ko.dependentObservable(...)
In addition, if your KO View model contains some numeric value make sure you change the comparison operators: from === to == and !== to != , so that type conversion is performed.
此外,如果您的 KO 视图模型包含一些数值,请确保更改比较运算符:从 === 到 == 和 !== 到 != ,以便执行类型转换。
I hope this helps others
我希望这对其他人有帮助
回答by cakefactory
Fixed the clearing of input on load problem for RP's Solution. Even though it's kind of an indirect solution, I changed this at the end of the function:
修复了 RP 解决方案加载时清除输入的问题。尽管这是一种间接解决方案,但我在函数末尾更改了它:
$(element).val(modelValue && inputValueProp !== valueProp ?
unwrap(modelValue[inputValueProp]) : modelValue.toString());
to this:
对此:
var savedValue = $(element).val();
$(element).val(modelValue && inputValueProp !== valueProp ? unwrap(modelValue[inputValueProp]) : modelValue.toString());
if ($(element).val() == '') {
$(element).val(savedValue);
}
回答by avid
I know this question is old, but I was also looking for a really simple solution for our team using this in a form, and found out that jQuery autocomplete raises an 'autocompleteselect' event.
我知道这个问题很老,但我也在为我们的团队寻找一个非常简单的解决方案,在表单中使用它,并发现jQuery 自动完成引发了一个 'autocompleteselect' 事件。
This gave me this idea.
这给了我这个想法。
<input data-bind="value: text, valueUpdate:['blur','autocompleteselect'], jqAutocomplete: autocompleteUrl" />
With the handler simply being:
处理程序只是:
ko.bindingHandlers.jqAutocomplete = {
update: function(element, valueAccessor) {
var value = valueAccessor();
$(element).autocomplete({
source: value,
});
}
}
I liked this approach because it keeps the handler simple, and it doesn't attach jQuery events into my viewmodel. Here is a fiddle with an array instead of a url as the source. This works if you click the textbox and also if you press enter.
我喜欢这种方法,因为它使处理程序保持简单,并且不会将 jQuery 事件附加到我的视图模型中。这是一个使用数组而不是 url 作为源的小提琴。如果您单击文本框并按 Enter,这将起作用。
回答by Dorian Farrimond
Another variation on Epstone's original solution.
Epstone 原始解决方案的另一个变体。
I tried to use it but also found that the view model was only being updated when a value was typed manually. Selecting an autocomplete entry left the view model with the old value, which is a bit of a worry because validation still passes - it's only when you look in the database you see the problem!
我尝试使用它,但也发现只有在手动输入值时才会更新视图模型。选择一个自动完成条目使视图模型保留旧值,这有点令人担忧,因为验证仍然通过 - 只有当您查看数据库时才会看到问题!
The method I used is to hook the select handler of the jquery UI component in the knockout binding init, which simply updates the knockout model when a value is chosen. This code also incorporates the dispose plumbing from George's useful answer above.
我使用的方法是在knockout binding init 中hook jquery UI 组件的select 处理程序,它只是在选择一个值时更新knockout 模型。这段代码还包含了上面 George 的有用答案中的处理管道。
init: function (element, valueAccessor, allBindingsAccessor) {
valueAccessor.select = function(event, ui) {
var va = allBindingsAccessor();
va.value(ui.item.value);
}
$(element).autocomplete(valueAccessor);
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).autocomplete("destroy");
});
}
...
<input class="form-control" type="text" data-bind="value: ModelProperty, ko_autocomplete: { source: $root.getAutocompleteValues() }" />
This is now working pretty well. It is intended to work against a preloaded array of values on the page rather than querying an api.
这现在工作得很好。它旨在针对页面上预加载的值数组而不是查询 api。
回答by Jerry
Niemeyer's solution is great, however I run into an issue when trying to use autocomplete inside a modal. Autocomplete was destroyed on modal close event (Uncaught Error: cannot call methods on autocomplete prior to initialization; attempted to call method 'option' ) I fixed it by adding two lines to the binding's subscribe method:
Niemeyer 的解决方案很棒,但是我在尝试在模态中使用自动完成功能时遇到了问题。自动完成在模式关闭事件中被破坏(未捕获错误:在初始化之前无法调用自动完成的方法;尝试调用方法 'option' )我通过向绑定的订阅方法添加两行来修复它:
mappedSource.subscribe(function (newValue) {
if (!$(element).hasClass('ui-autocomplete-input'))
$(element).autocomplete(options);
$(element).autocomplete("option", "source", newValue);
});