我有一个jQueryUI的自动完成从客户列表拉并基于选择[输入数据角色=“客户搜索”]附后。 一旦客户选择,我做一个AJAX调用,以获得完整的客户详细信息。 这部分我都工作正常。 问题是,我无法找出一个方法,将进入淘汰赛此。 我理想的情况是一个自定义样结合“ONSELECT:顾客选择”,这将需要在选定的客户JSON,并将其纳入整体模型,然后这将导致更新页面上的一堆领域与bingings如model.Customer 。地址,model.Customer.Type。
我撞我的头的地方是连接点我已经得到了客户的JSON从AJAX调用,如何将其发送到“顾客选择的”方法上的视图模型绑我附上了jQuery自动完成相同的输入回来之后。
这里是一个bindinghandler我的团队写了处理自动完成的简化版本。 当选择了一个项目时,该项目被插入到视图模型可观察到的阵列。 它必然以下述方式:
<input type="text" data-bind="autoComplete:myObservableArray, source:'myUrl'" />
您可以自定义时,在“ 选择:”选择了一个项目会发生什么区域。
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);
}
}
});
}
};
我们希望,这是这样的,你要寻找的。 如果你需要澄清的东西,让我知道。
注意:除了jQuery和淘汰赛中,这个例子中使用underscore.js( 在_.any()函数 )
valueUpdate:模糊
data-bind="value: textbox, valueUpdate: blur"
结合固定的问题对我来说:
$(function() { $(".autocomplete").autocomplete({ source: [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Scheme"] }); }); var viewModel = { textbox: ko.observable() }; ko.applyBindings(viewModel);
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="//code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script> <input type="text" class="autocomplete" data-bind="value: textbox, valueUpdate: blur"/>