可观察数组内部的可观察数组,可跟踪两个元素KO js

时间:2019-06-21 14:02:11

标签: javascript knockout.js

Site Screen Shot

3个单选框和输入文本捆绑在一起的数组,选择单选会动态弹出用户可以在其上面添加的文本。我能够填充文本框,但是之后无法跟踪两者的变化,因为我需要某种可观察的东西来跟踪两者的变化并为我提供两者的总价值(例如'File:c:\ temp \ data。 cs'

这是我的HTML

  <!-- ko foreach: includes  -->

                <div class="col-md-3 mt-3 offset-3 ">
                    <input class="col-md-2 " type="radio" value="file:" data-bind="checked: type, attr: { name: name }">File
                    <input class="col-md-2" type="radio" value="dir:" data-bind="checked: type, attr: { name: name }">Dirs
                    <input class="col-md-2" type="radio" value="glob:" data-bind="checked: type, attr: { name: name }">Glob
                </div>

                <div class=" col-md-6 pt-3 ">
                    <input type="text" class="form-control" required data-bind="attr: { name: name } , value: value">
                </div>
                <!-- /ko -->
            </div>

            <div class="col-sm-3 mt-4 mb-4 offset-4" id="firstPath">
                <button type="button" class="form-control btn btn-info ml-3" data-bind="click: addInclude">Add new include line</button>
            </div>

还有我的JS

self.includes = ko.observableArray([{
        name: "package[][includes][0]",
        type: "file:",
        value: ko.observable()
    }]);


self.addInclude = function () {
 self.includes.push({
            name: `package[][includes][${includeCounter++}]`,
            type: `file`,
            value: ko.observable("file")
        });
    };

如何使value属性包含在可观察数组中,以跟踪单选和相关行的输入文本值? 我尝试了Ko.Computed,但问题是在初始化包含include observable的类型时尚未定义相对行(类型的默认值为file)

1 个答案:

答案 0 :(得分:0)

类型成员应该是可观察的。因此,通过订阅,您可以在每次类型更改时设置value的值。

function myViewModel() {
  var self = this;

  self.includeCounter = 0;

  self.includes = ko.observableArray([]);

  self.addInclude = function () {
    var type = ko.observable('file:');
    var value = ko.observable('file:');
    type.subscribe((newValue) => {
      value(newValue);
    }, self);

    var item = {
      name: `package[][includes][${self.includeCounter++}]`,
      type: type,
      value: value
    };
    self.includes.push(item);
  };

  self.addInclude();
}

var vm = new myViewModel();
ko.applyBindings(vm);