问题描述
我有一个按钮,可将项目在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支持移动项目. 更新:从版本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中的两个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!