Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
930 views
in Technique[技术] by (71.8m points)

knockout.js - Knockoutjs: index param is always 0 in beforeRemove callback of foreach binding

According to documentation, the beforeRemovecallback in foreach binding will supply the following parameters to your callback:

  1. A DOM node being added to the document
  2. The index of the added array
  3. element The added array element

But I am getting 0 always in the index param of my callback function. Can somebody tell my what's wrong? Here is the code:

https://codepen.io/gxzzin/pen/KKNPKeO?editors=1010

question from:https://stackoverflow.com/questions/65923407/knockoutjs-index-param-is-always-0-in-beforeremove-callback-of-foreach-binding

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Looks like a bug in knockout 3.5.0. The same code works with version 3.4.2, have a look at the abbreviated example below:

function RootViewModel(){
  var self = this;
  self.Items = ko.observableArray([1, 2, 3, 4, 5]);

  self.BeforeRemove = function(element, ind, item) {
    console.log("Index: " + ind);
    $(element).remove();
  };
};

ko.applyBindings(new RootViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div class="container p-5">

  <button data-bind="click: function () { Items.push(Items().length + 1) }">Add</button>

  <ul data-bind="foreach: { data: Items, beforeRemove: BeforeRemove }">
    <li data-bind="text: $data, click: function (i) { $root.Items.remove(i) }"></li>
  </ul>

</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...