【问题标题】:Dynamic Content Being Obserable With Knockout动态内容可通过 Knockout 观察
【发布时间】:2012-06-20 07:50:45
【问题描述】:

我创建了一个函数,它返回我的 html 页面中的所有 obserables 项目。这个函数的一个例子是

<input type="text" id="frmIn1-Officer" data-bind="value: AOfficer" class="InputText"/>
<input type="text" id="frmIn1-Officer" data-bind="value: AOfficer2" class="InputText"/>
<input type="text" id="frmIn1-Officer" data-bind="value: AOfficer3" class="InputText"/>
<input type="text" id="frmIn1-Officer" data-bind="value: AOfficer4" class="InputText"/>

函数将返回 ['AOfficer','AOfficer2','AOfficer3','AOfficer4']

现在我想让上面的数据绑定元素列表变得可观察

viewModel = {
AOfficer : ko.observable(),
AOfficer2 : ko.observable(),
AOfficer3 : ko.observable(),
AOfficer4 : ko.observable(),
}
ko.applyBindings(viewModel);

以上是这样做的非动态方式..但我似乎无法找到解决这个问题的动态方式..

我将如何解决这个问题?有解决办法吗?解决方法?

谢谢大家

【问题讨论】:

    标签: javascript html dynamic knockout.js observable


    【解决方案1】:

    我过去使用的一个选项是创建一个自定义绑定,它将根据现有值为您填充视图模型。

    类似:

    ko.bindingHandlers.valueWithInit = {
        init: function(element, valueAccessor, allBindingsAccessor, data) {
            var property = valueAccessor(),
                value = element.value;
    
            //create the observable, if it doesn't exist 
            if (!ko.isWriteableObservable(data[property])) {
                data[property] = ko.observable();
            }
            data[property](value);
    
            ko.applyBindingsToNode(element, { value: data[property] });
    
        }
    };
    

    添加绑定时,需要将属性名指定为字符串,这样在最初不存在时绑定不会失败。

    此方法将为您创建一个 observable,如果它不存在或只是用元素的值填充现有的 observable。

    示例:http://jsfiddle.net/rniemeyer/BnDh6/

    【讨论】:

      【解决方案2】:

      也许您可以尝试将其设为 observableArray():

      var Officers = ko.observableArray([{name: AOfficer1, o_value: xxx},{name: AOfficer2, o_value: yyy}, and so on]);
      

      然后你的 HTML 放:

      <ul data-bind="foreach: Officers">
      <li><span data-bind="text: name"></span><input type="text" data-bind="value: o_value" class="InputText"/></li>
      </ul>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-13
        • 2016-01-25
        • 1970-01-01
        • 2015-10-23
        • 2014-12-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多