当我使用 jquery 自动完成功能并选择一些可能的值时,尝试更新 knockoutjs 生成的列表。但是当我在 Select 方法中调用 addItem 函数时,列表不会更新。预期的行为是将选定的项目值添加到 knockoutjs 项目数组。
MVC3 示例视图:
<input type="text" id="Name"/>
<h4>Items</h4>
<ul data-bind="foreach: items">
<li>
<span data-bind="text: $index"></span>:
<span data-bind="text: name"></span>
<span data-bind="text: code"></span>
<a href="#" data-bind="click: $parent.removeItem">Remove</a>
</li>
</ul>
<script type="text/javascript">
$(function () {
var appViewModel = new AppViewModel();
function AppViewModel() {
var self = this;
self.items = ko.observableArray([]);
self.addItem = function (name, code) {
self.items.push({ name: name, code: code });
};
self.removeItem = function () {
self.items.remove(this);
};
}
$('#Name').autocomplete({
minLength: 1,
delay: 500,
source: function (request, response) {
$.ajax({
type: "POST",
url: "/Home/SearchItems",
dataType: "json",
data: { searchText: request.term },
success: function (data) {
if (data != undefined) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
code: item.Code
};
}));
}
}
});
},
select: function (event, ui) {
appViewModel.addItem(ui.item.value, ui.item.code);
}
});
ko.applyBindings(new AppViewModel());
});
</script>