JSFiddle - React, Tailwind, and code Playground
by ingro
HTML
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/base/jquery-ui.css">
<script src="https://raw.github.com/SteveSanderson/knockout/master/build/output/knockout-latest.debug.js"></script>
<div data-bind="template: { name: 'contact-template', data: Contact1 }"></div>
<hr/>
<div data-bind="template: { name: 'contact-template', data: Contact2 }"></div>
<script type="text/html" id="contact-template">
<pre data-bind="text: JSON.stringify(ko.toJS($data),null,2)"></pre>
<div>
Name
<input data-bind="uniqueName: true,
jqAuto: { autoFocus: true },
jqAutoSource: $root.Contacts,
jqAutoQuery: getContacts,
jqAutoValue: SelectedContact.Name,
jqAutoSourceLabel: 'Name',
jqAutoSourceInputValue: 'Name'"
class="name" />
</div>
<div style="display:''">
<div>
Company
<input data-bind="value: Company, uniqueName: true" class="company" />
</div>
<div>
Address
<input data-bind="text: Address1, value: Address1, uniqueName: true" class="address1" />
</div>
</div>
</script>
JavaScript
//jqAuto -- main binding (should contain additional options to pass to autocomplete)
//jqAutoSource -- the array to populate with choices (needs to be an observableArray)
//jqAutoQuery -- function to return choices
//jqAutoValue -- where to write the selected value
//jqAutoSourceLabel -- the property that should be displayed in the possible choices
//jqAutoSourceInputValue -- the property that should be displayed in the input box
//jqAutoSourceValue -- the property to use for the value
ko.bindingHandlers.jqAuto = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
var options = valueAccessor() || {},
allBindings = allBindingsAccessor(),
unwrap = ko.utils.unwrapObservable,
modelValue = allBindings.jqAutoValue,
source = allBindings.jqAutoSource,
query = allBindings.jqAutoQuery,
valueProp = allBindings.jqAutoSourceValue,
inputValueProp = allBindings.jqAutoSourceInputValue || valueProp,
labelProp = allBindings.jqAutoSourceLabel || inputValueProp;
//function that is shared by both select and change event handlers
function writeValueToModel(valueToWrite) {
if (ko.isWriteableObservable(modelValue)) {
modelValue(valueToWrite);
} else { //write to non-observable
if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers']['jqAutoValue']) allBindings['_ko_property_writers']['jqAutoValue'](valueToWrite);
}
}
//on a selection write the proper value to the model
options.select = function(event, ui) {
writeValueToModel(ui.item ? ui.item.actualValue : null);
};
//on a change, make sure that it is a valid value or clear out the model value
options.change = function(event, ui) {
var currentValue = $(element).val();
var matchingItem =...