问题描述
我有一个 jQueryUI 自动完成功能,它从客户列表中提取并根据选择器 [input data-role="customer-search"] 进行附加.选择客户后,我会进行 AJAX 调用以获取完整的客户详细信息.这部分我工作正常.问题是我在想办法将淘汰赛纳入其中时遇到了麻烦.我的理想情况是像onSelect:customerSelected"这样的自定义绑定,它会接收选定的 Customer JSON 并将其集成到整个模型中,然后这会导致更新页面上的一堆字段,并带有诸如 model.Customer 之类的 bingings.地址、型号.客户.类型.
I have a jQueryUI autocomplete that pulls from a list of customers and is attached based on the selector [input data-role="customer-search"]. Once a customer is selected, I make a AJAX call to get the full customer detail. This part I have working fine. The issue is that I am having trouble figuring out a way to incorporate knockout into this. My ideal situation is a custom binding like "onSelect: customerSelected", which would take in the selected Customer JSON and integrate it into the overall model, which would then cause updates to a bunch of fields on the page with bingings such as model.Customer.Address, model.Customer.Type.
在我从 AJAX 调用中取回 Customer JSON 之后,我遇到的问题是连接点,如何将它发送到绑定到与我附加的相同输入的视图模型上的customerSelected"方法jQuery 自动完成.
The place I am butting my head against is that connection point after I've gotten the Customer JSON back from the AJAX call, how to send it to the "customerSelected" method on the viewmodel tied to the same input I attached the jQuery autocomplete.
推荐答案
这是我的团队为处理自动完成而编写的 bindinghandler 的简化版本.当一个项目被选中时,该项目被插入到视图模型中的一个可观察数组中.其绑定方式如下:
Here is a simplified version of a bindinghandler my team wrote for handling autocomplete. When an item is selected, the item is inserted into an observable array in the view model. It is bound in the following manner:
<input type="text" data-bind="autoComplete:myObservableArray, source:'myUrl'" />
您可以自定义在选择:"区域中选择项目时发生的情况.
You can customize what happens when an item is selected in the 'select:' area.
ko.bindingHandlers.autoComplete = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var postUrl = allBindingsAccessor().source; // url to post to is read here
var selectedObservableArrayInViewModel = valueAccessor();
$(element).autocomplete({
minLength: 2,
autoFocus: true,
source: function (request, response) {
$.ajax({
url: postUrl,
data: { term: request.term },
dataType: "json",
type: "POST",
success: function (data) {
response(data);
}
});
},
select: function (event, ui) {
var selectedItem = ui.item;
if (!_.any(selectedObservableArrayInViewModel(), function (item) { return item.id == selectedItem.id; })) { //ensure items with the same id cannot be added twice.
selectedObservableArrayInViewModel.push(selectedItem);
}
}
});
}
};
希望这就是您正在寻找的东西.如果您需要澄清一些问题,请告诉我.
Hopefully, it's something like this that you're looking for. If you need something clarified, let me know.
注意除了jquery和knockout之外,这个例子还使用underscore.js(_.any()函数)
Note Besides jquery and knockout, this example uses underscore.js ( the _.any() function)
这篇关于连接淘汰赛和 jQueryUI 自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!