I prefer to keep the list of auto-complete suggestions completely separate from the knockout. I want Knockout to find out as soon as the user has actually entered the value.
This is closer to user2576666 because it uses Typeahead user events to force updates in the knockout model when there is a choice or auto-completion. However, it does not require special typeahead bindings and does not require values to be stored in the ViewModel knockout module. This opens up possibilities for a more customizable line termination (for example, using Bloodhound ), which will be uselessly confused if we try to save this in a knockout model. My ViewModel is definitely not suitable for storing autocomplete options for my use case (and, I would suggest, many others, especially if you have a potentially large list that requires a dynamic collection). IMO of this version is also easier to understand:
var availableProducts = ['One', 'Two', 'Three']; var substringMatcher = function(strs) { return function findMatches(q, cb) { var matches, substrRegex; matches = []; substrRegex = new RegExp(q, 'i'); $.each(strs, function(i, str) { if (substrRegex.test(str)) { matches.push({ value: str }); } }); cb(matches); }; }; function MyModel(){ var self = this; self.productName = ko.observable(); } var myModel = new MyModel(); ko.applyBindings(myModel); var onUpdated = function($e, datum) { myModel.productName(datum.value); }; $(".typeahead") .typeahead( {hint: true, minLength: 1, highlight: true}, {displayKey: 'value', source: substringMatcher(availableProducts)}) .on('typeahead:autocompleted', onUpdated) .on('typeahead:selected', onUpdated); // for knockoutJS
Of course, I saved this as a JSFiddle :
Andy MacKinlay
source share