如何交换 observableArray 中的两个项目? [英] How do I swap two items in an observableArray?

查看:21
本文介绍了如何交换 observableArray 中的两个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮,可以将一个项目在 observableArray 中向左移动一个位置.我正在按照以下方式进行操作.然而,缺点是 category()[index] 从数组中删除,从而丢弃该节点上的任何 DOM 操作(在我的情况下通过 jQuery 验证).

I have a button that moves an item one position left in an observableArray. I am doing it the following way. However, the drawback is that categories()[index] gets removed from the array, thus discarding whatever DOM manipulation (by jQuery validation in my case) on that node.

有没有办法在不使用临时变量的情况下交换两个项目以保留 DOM 节点?

Is there a way to swap two items without using a temporary variable so as to preserve the DOM node?

    moveUp: function (category) {
        var categories = viewModel.categories;
        var length = categories().length;
        var index = categories.indexOf(category);
        var insertIndex = (index + length - 1) % length;

        categories.splice(index, 1);
        categories.splice(insertIndex, 0, category);
        $categories.trigger("create");
    }

推荐答案

这是我的 moveUp 版本,它一步完成交换:

Here's my version of moveUp that does the swap in one step:

moveUp: function(category) {
    var i = categories.indexOf(category);
    if (i >= 1) {
        var array = categories();
        categories.splice(i-1, 2, array[i], array[i-1]);
    }
}

尽管如此,这仍然不能解决问题,因为 Knockout 仍会将交换视为删除和添加操作.不过,Knockout 有一个未决问题,用于支持移动项目.更新:从 2.2.0 版开始,Knockout 确实可以识别移动的项目,并且 foreach 绑定不会重新渲染它们.

That still doesn't solve the problem, though, because Knockout will still see the swap as a delete and add action. There's an open issue for Knockout to support moving items, though. Update: As of version 2.2.0, Knockout does recognize moved items and the foreach binding won't re-render them.

这篇关于如何交换 observableArray 中的两个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆