JSFiddle - React, Tailwind, and code Playground
HTML
<div data-bind="foreach: records">
<div data-bind="foreach: $data">
<label data-bind="text: id"></label>
<span data-bind="polyInput:$data, optionsText:'optTxt', optionsValue: 'optId'"></span>
<!-- <select data-bind="attr: {id: id}, style: {width: size}, value: value, options: options, optionsText: 'optTxt', optionsValue: 'optId'"></select>
<!-- <input type="text" data-bind="attr: {id: id}, style: {width: size}, value: value" />
<!-- <span data-bind="text: value"></span>
</div>
</div>
JavaScript
ko.bindingHandlers.polyInput = {
init: function (element, valueAccessor, allBindingsAccessor, data, context) {
var data = valueAccessor(), newElement;
if (data.type == 'select') {
newElement = document.createElement('SELECT');
ko.bindingHandlers.style.update(newElement, ko.observable({width:data.size}));
}
else if (data.type == 'input') {
newElement = document.createElement('INPUT');
}
else if (data.type == 'mu') {
newElement = document.createTextNode(data.value);
}
else {
alert("Unhandled type:" + data.type);
}
element.appendChild(newElement);
},
update: function (element, valueAccessor, allBindingsAccessor, data, context) {
var newElement = element.children[0];
if (data.type == 'select' || data.type == 'input') {
ko.bindingHandlers.style.update(newElement, ko.observable({width:data.size}));
ko.bindingHandlers.value.update(newElement, ko.observable(data.value));
}
if (data.type == 'select') {
ko.bindingHandlers.options.update(newElement, function () { return data.options; }, allBindingsAccessor, data, context);
}
}
};
function Model() {
records = ko.observableArray([
[{
type: "input",
id: "Date",
size: "100px",
value: ko.observable('testDate')
}, {
type: "select",
id: "Weather",
size: "100px",
value: ko.observable(),
options: [{
optId: "w1",
optTxt: "Cloudy"
}, {
optId: "w2",
optTxt: "Sunny"
}, {
optId: "w3",
optTxt: "Rainy"
}, {
optId: "w4",
optTxt: "Snowy"
}, {
optId: "w5",
optTxt: "Foggy"
...