简体   繁体   English

如何从配置文件中读取数据绑定属性值并将其绑定到视图

[英]How to read data-bind property value from config file and bind i to view

In knockout, I need to take the property and value to bind from a configuration file and bind it to view. 在淘汰赛中,我需要将属性和值从配置文件中绑定并绑定到视图。 How can I achieve that? 我该如何实现?

eg 例如

<tbody data-bind="foreach: {data: data, as : 'tbData'}">
  <!-- ko foreach: $parent.bindingProperties -->
    <input type="text" data-bind="value:tbData.spec"/>
  <!-- /ko -->
//some code
</tbody>

I need to read "value:tbData.spec" from js file. 我需要从js文件中读取“ value:tbData.spec”。 How can I write a suitable JS function and bind it to the view by calling it? 如何编写合适的JS函数并通过调用将其绑定到视图?

The configuration file is a js file. 配置文件是一个js文件。 The config file is like 配置文件就像

bindingProperties : [{'value': 'tbData.spec'}]

I'm not sure how you're currently loading the configuration file, but if you can dump its contents into an observable, here's how you could go about binding it to the UI. 我不确定您当前如何加载配置文件,但是如果可以将其内容转储到可观察的文件中,则可以使用以下方法将其绑定到UI。 I've made a quick binding that will manually apply other bindings by name-value pairs. 我做了一个快速绑定,它将通过名称-值对手动应用其他绑定。 It's not something I've used before so it's not well tested and it's certainly not robust just more of a proof of concept. 这不是我以前使用过的东西,因此没有经过充分测试,当然也没有足够的概念证明。

ko.bindingHandlers.applyBindings = {
    update: function(element, valueAccessor, allBindingsAccessor, data, bindingContext) {
        var bindings = ko.unwrap(valueAccessor()) || {}; //should be an object with multiple properties like: { bindingName: propertyName }
        for (var name in bindings) {
            if (bindings.hasOwnProperty(name)) {
                var binding = {};
                var target = data[bindings[name]];
                binding[name] = function () { return target; };

                ko.applyBindingAccessorsToNode(element, binding, bindingContext);
            }
        }
    }
}

and here's a jsFiddle of it in action: fiddle 这是一个起作用的jsFiddle: 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM