KnockoutJS UI助手绑定

时间:2013-07-26 10:23:07

标签: knockout.js custom-binding

我正在使用KnockoutJS进行一些UI自动化。我的问题很简单;在使用KnockoutJS时,我想创建类似的东西:

<div data-bind="textboxFor: FirstName"></div>

使用自定义绑定。结果应该是:

<!-- 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>

我试过了:

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.
    }
};

但这不适用于

ko with: Person
绑定。 其次,我检索绑定属性的名称的方式感觉并且看起来非常 iffy 。也许有人可以指导我找到更好的解决方案。

提前感谢你的时间和耐心! 卡洛斯

1 个答案:

答案 0 :(得分:-1)

这种东西已内置于Knockout中,请查看模板绑定:http://knockoutjs.com/documentation/template-binding.html。我很确定你会完成你想要实现的目标。