Here is a simplified version of the binding handler that my team wrote to handle autocomplete. When an item is selected, the item is inserted into the observed array in the view model. It is connected as follows:
<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); } } }); } };
Hope this looks like what you are looking for. If you need something clarified, let me know.
Note In addition to jquery and knockout, this example uses the underscore.js function (_.any () function)
source share