knockoutjs 数据绑定在内循环中不起作用

knockoutjs data-bind not working in inner loop

案例 1: -- 工作

HTML

Test::<span data-bind="text: $parent.testText"></span>
<button  data-bind="click: $parent.testbtn"></button>

JS

numberOfClicks : ko.observable(0),
incrementClickCounter : function() {
 alert('click called..');
 var previousCount = this.numberOfClicks();
 this.numberOfClicks("Testtttt....");
}

案例 2: -- 工作

HTML

<!-- ko foreach: { data: loop1(), as: 'styleColor'} -->
 Test::<span data-bind="text: $parent.testText"></span>
 <button  data-bind="click: $parent.testbtn"></button>
<!-- /ko -->

案例 3: -- 不工作

HTML

<!-- ko foreach: { data: loop1(), as: 'styleColor'} -->
 <div class="standard-color" data-bind="foreach: $parent.loop2()">                    
     Test::<span data-bind="text: $parent.testText"></span>
     <button  data-bind="click: $parent.testbtn"></button>
 </div>
<!-- /ko -->

当我点击按钮时,js函数没有调用。

您应该能够嵌套多个 foreach 循环,即使它们从父层获取数据。您必须意识到,这些循环中的每一个都会在绑定上下文中创建一个新层。获得正确的 $parent 可能会成为一项棘手的练习...

我的建议是将一些循环逻辑移动到您的视图模型中。

这是一个执行嵌套循环的示例:

(function() {
  const colors = ["red", "yellow", "blue"];
  const styles = ["glossy", "matte"];

  const selectedColor = ko.observable("red");
  const selectedStyle = ko.observable("glossy");

  const select = (color, style) => {
    selectedColor(color);
    selectedStyle(style);
  }

  ko.applyBindings(
    { colors, styles, selectedColor, selectedStyle, select }
  );
}());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<h1>Your selection: <span data-bind="text: selectedColor"></span>, <span data-bind="text: selectedStyle"></span></h1>

<ul data-bind="foreach: { data: colors, as: 'color' }">
  <!-- ko foreach: { data: $parent.styles, as: 'style' } -->
  <li data-bind="
    click: $parents[1].select.bind(null, color, style),
    text: color + ', ' + style"></li>
  <!-- /ko -->
</ul>

这是一个将一些逻辑移至 JS 的示例:

(function() {
  const colors = ["red", "yellow", "blue"];
  const styles = ["glossy", "matte"];

  const options = colors.flatMap(color =>
    styles.map(style => ({ color, style, label: `${color}, ${style}` }))
  )

  const selectedOption = ko.observable(options[0]);

  ko.applyBindings(
    { options, selectedOption }
  );
}());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<h1 data-bind="with: selectedOption">
  Your selection: <span data-bind="text: label"></span>
</h1>

<ul data-bind="foreach: options">
  <li data-bind="
    click: $parent.selectedOption,
    text: label"></li>
</ul>