我正在使用 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.
}
};
但这不适用于
与:人捆绑。其次,我检索绑定属性名称的方式感觉和看起来都非常不确定。也许有人可以指导我找到更好的解决方案。
提前感谢您的时间和耐心!卡洛斯