I'm working on some UI automation using KnockoutJS. My question is fairly simple; While using KnockoutJS I would like to create something like:
<div data-bind="textboxFor: FirstName"></div>
with a custom binding. The endresult should look like:
<!-- Name -->
<div class="control-group">
<label class="control-label" for="txtFirstName">FirstName:</label>
<div class="controls">
<input id="txtFirstName" type="text" data-bind="value: FirstName" />
</div>
</div>
I have tried:
ko.bindingHandlers.textboxFor = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var propertyName, display;
var valueList = element.attributes['data-bind'].nodeValue.split(',');
valueList.forEach(function (node) {
if (node.indexOf('textboxFor') !== -1) {
propertyName = node.split(':')[1].trim();
}
});
if (!viewModel.translations) {
display = propertyName.charAt(0).toUpperCase() + propertyName.slice(1);
}
else {
display = viewModel.translations[propertyName];
}
var _innerHTML = "<label class='control-label' for='txt" + propertyName + "'>" + display + ":</label>" +
"<div class='controls'>" +
"<input id='txt" + propertyName + "' type='text' data-bind='value: " + propertyName + "' />" +
"</div>";
element.className = "control-group";
element.innerHTML = _innerHTML;
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
// This will be called once when the binding is first applied to an element,
// and again whenever the associated observable changes value.
// Update the DOM element based on the supplied values here.
}
};
But this does not work with a
ko with: Personbinding. Secondly, the way I retrieve the name of the bound property feels and looks quite iffy. Maybe someone could direct me to a better solution.
Thank's in advance for your time and patience! Carlos