javascript - 无法使用 knockout 和 knockout-sortable 在正确的索引处插入对象

标签 javascript knockout.js jquery-ui-sortable knockout-sortable

我目前正在尝试使用 knockout-sortable 开发一个小函数,它应该按如下方式工作。

我有 3 个可观察的集合:第一个是空的可放置区域,第二个包含集合中的前 3 个项目(可见),第三个包含我的数据集的其余部分(隐藏)。当将第二个集合中的项目拖到第一个集合中时,第三个数组中与刚刚移动的项目的“group”属性匹配的第一个项目需要插入到与被移动项目相同索引处的第二个可观察对象中刚拖出来。这一切似乎都有效,除了在第一个索引处从第三个数组向第二个数组添加一个项目时,它总是在数组的后面结束。我什至添加了一个 if 语句,它将使用 unshift 来解决这个问题,但它似乎不起作用。任何帮助将非常感激。这是我尝试将对象插入正确索引的代码片段。

self.GetNextItemForClass = function(group, sourceIndex) {
  var nextItem = ko.utils.arrayFirst(self.lowPriorityTasks(), function(item) {
    if (item == null)
      return null;

    return item.group() === group;
  });

  if (nextItem != null) {
    var items = self.lowPriorityTasks();
    if (sourceIndex == 0) {
      self.normalPriorityTasks.unshift(nextItem);
    } else {
      self.normalPriorityTasks.splice(sourceIndex, 1, nextItem, items[sourceIndex]);
      ko.utils.arrayRemoveItem(self.lowPriorityTasks(), nextItem);
    }
  }
}

我有一把 fiddle here试图说明我面临的问题。

最佳答案

要在数组的第 n 索引处插入一个 item,您需要调用:

array.splice(n, 0, item);

您正在调用 splice具有 4 个参数的函数。因此 items[sourceIndex] 正在向 normalPriorityTasks 添加一个额外的项目。

// all parameters after the 2nd get added to the array
array.splice(start, deleteCount, item1, item2, ...) 

splice 中删除第四个参数并将您的函数更改为:

self.GetNextItemForClass = function(group, sourceIndex) {
  var nextItem = ko.utils.arrayFirst(self.lowPriorityTasks(), function(item) {
    if (item == null)
      return null;

    return item.group() === group;
  });

  if (nextItem != null) {
    var items = self.lowPriorityTasks();

    // splice works for zero index as well
    // remove the forth argument from this call
    self.normalPriorityTasks.splice(sourceIndex, 0, nextItem);
    self.lowPriorityTasks.remove(nextItem); // use remove
  }
}

Here's an updated fiddle

关于javascript - 无法使用 knockout 和 knockout-sortable 在正确的索引处插入对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47459737/

相关文章:

javascript - jqgrid 自定义格式化程序 : The custom formatter always returns the last row of the grid. 为什么?

javascript - 输入类型的动态默认值不起作用

javascript - 使用 jquery/javascript 放大和缩小(绝对坐标不变)

javascript - Knockout observableArray 不更新多个 View 模型

javascript - 使用上次迭代中的变量在循环中创建的 knockout 计算

javascript - 将 true/false 绑定(bind)到 Knockout JS 中的单选按钮

javascript - 连接到 fancytree 的可排序在拖放时忘记了其位置

javascript - jQuery UI 可排序 : load order from array

javascript - 在 Jquery DataTable 中启用 deferRendering 的正确方法是什么

javascript - 使用 jQuery sortable 交换两个 div