Trying to update knockoutjs generated list, when i use jquery autocomplete functionality and select some possible values. But list doesn’t update when i call the addItem function inside Select method. Expected behaviour would be that selected item value are added to knockoutjs items array.
MVC3 example view:
<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>
Here is a working version: http://jsfiddle.net/jearles/vya7V/
Your problem was that you were instantiating a new AppViewModel in the
ko.applyBindingsstatement, rather than passing inappViewModelthat you instantiated earlier and are using in theselect.