How do I swap two items in an observableArray?

后端 未结 4 1866
轮回少年
轮回少年 2020-12-03 05:05

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 f

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 05:56

    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]);
        }
    }
    

    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.

提交回复
热议问题