0

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: Person
binding. 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

Mr. Baudin
  • 2,104
  • 2
  • 16
  • 24

1 Answers1

-1

This kind of thing is already built in to Knockout, have a look at the template binding: http://knockoutjs.com/documentation/template-binding.html. I'm pretty sure that'll do exactly what you're trying to achieve.

DoctorMick
  • 6,703
  • 28
  • 26
  • Thank you for your reply, but templates are not really what I'm looking for. Templates are defined using a script tag in some random piece of html code. I want this functionality as a part of my framework, so modularly. – Mr. Baudin Jul 29 '13 at 11:20